How to respond with differe...
How to respond with differe...
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?":
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].
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:
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:
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 provides a way to set HTTP status codes by throwing errors with specific extensions. For example:
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].
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].
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].
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].
Centralized Error Handling: Implement a centraliz...
expert
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào