strawberry-graphql / strawberry

A GraphQL library for Python that leverages type annotations 🍓
https://strawberry.rocks
MIT License
3.93k stars 519 forks source link

Allow errors to set HTTP status codes #2399

Open patrick91 opened 1 year ago

patrick91 commented 1 year ago

Discussed in https://github.com/strawberry-graphql/strawberry/discussions/2304

Originally posted by **ShourovRoy** November 2, 2022 Apollo Graphql has a function to modify status code on error that can be overridden which plays an important role for implementing refresh token. Is there any way to do that here?

Apollo server allows errors to change the status code, maybe we can do the same:

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'],
            ]),
          },
        },
      });
    },
  },
};

https://www.apollographql.com/docs/apollo-server/data/errors/#setting-http-status-code-and-headers

Upvote & Fund

Fund with Polar

erikwrede commented 11 months ago

I'm somewhat critical of setting the http status right in the base GraphQL error, as the Schema is transport-agnostic. Maybe we can create a new Http or StatusCode GraphQLError with a middleware for the HTTP/Websocket/(in the future SSE) views that injects the code based on the new Error class.