Câu hỏi phỏng vấn GraphQL
Câu hỏi

How to respond with differe...

Câu trả lời

Responding with different status codes in GraphQL can be a bit nuanced compared to traditional REST APIs. Here’s a comprehensive answer to the interview question "How to respond with different status codes in GraphQL?":

Understanding GraphQL and HTTP Status Codes

GraphQL typically returns a 200 OK status code for all responses, even if there are errors within the response. This is because GraphQL is designed to handle errors within the response body itself, rather than relying solely on HTTP status codes. The response will include a data field for successful parts of the query and an errors field for any issues encountered during execution[2][10].

Customizing HTTP Status Codes

While the default behavior is to return 200 OK, it is possible to customize HTTP status codes in GraphQL, though this requires additional implementation at the server level. Here are some methods and best practices:

Using GraphQLite

GraphQLite allows you to throw exceptions that can set specific HTTP status codes. For example, you can throw a GraphQLException with a custom status code:

php Copy
use TheCodingMachine\GraphQLite\Exceptions\GraphQLException;

throw new GraphQLException("Not found", 404);

This will generate a response with a 404 Not Found status code[1].

Apollo Server

Apollo Server provides a way to set HTTP status codes by throwing errors with specific extensions. For example:

javascript Copy
import { GraphQLError } from 'graphql';

const resolvers = {
  Query: {
    someField() {
      throw new GraphQLError('the error message', {
        extensions: {
          code: 'SOMETHING_BAD_HAPPENED',
          http: {
            status: 404,
            headers: new Map([
              ['some-header', 'it was bad'],
              ['another-header', 'seriously'],
            ]),
          },
        },
      });
    },
  },
};

This approach allows you to set both the status code and custom headers[3].

Express-GraphQL

In express-graphql, you can customize the error handling by using middleware to set the status code before the response is sent. However, it is generally recommended to handle errors within the GraphQL response rather than relying on HTTP status codes[4].

Best Practices

  1. Use the errors Field: Always include detailed error information in the errors field of the GraphQL response. This field can include custom error codes and messages that provide more context to the client[10][11].

  2. Custom Error Types: Define custom error types and use the extensions field to add additional metadata, such as error codes, timestamps, and other relevant information[11][12].

  3. Centralized Error Handling: Implement a centraliz...

expert

expert

Gợi ý câu hỏi phỏng vấn

entry

Is GraphQL a Database Technology?

junior

How to do Error Handling in GraphQL?

entry

Is GraphQL only for React/JavaScript Developers?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào