99designs / gqlgen

go generate based graphql server library
https://gqlgen.com
MIT License
9.98k stars 1.17k forks source link

gqlgen only return 200 error #2487

Open meghavinam opened 1 year ago

meghavinam commented 1 year ago

I want to return Http status code errors(400,500) in gqlgen Graphql Query

I tried

"github.com/vektah/gqlparser/v2/gqlerror"

err := gqlerror.Error{
        Message: "Invalid Data",
        Extensions: map[string]interface{}{
            "code": 400,
        },
    }

this method.But its return 200 APi response with this error body.

How to change this 200 error to 400 error in GQL API?

flymedllva commented 1 year ago

Hi!

Look at the function NewDefaultServer from the handler package, it implements the POST transport in the transport package, which is exactly where the server forms the user response to the POST request to the GraphQL schema. You can implement your POST by handling the error as you want before calling the writeJson function in (h POST) Do(w http.ResponseWriter, r *http.Request, exec graphql.GraphExecutor)

https://github.com/99designs/gqlgen/blob/cf1607ad8fe83ccc8322a0a77dc82b0fa3ff8489/graphql/handler/transport/http_post.go#L89

cristiprg commented 1 year ago

@meghavinam I agree with @FlymeDllVa, essentially the GrahpQL specification does not mention anything about the implementation, it could be REST, gRPC, your own protocols etc. Therefore, bringing REST-style specs into GraphQL isn't desirable.

You're using Extenstions correctly in your example, and your GraphQL client can make decisions based on the those bespoke codes but the GraphQL request itself is essentially successful.

That's just my opinion

wiegell commented 1 year ago

@meghavinam I agree with @FlymeDllVa, essentially the GrahpQL specification does not mention anything about the implementation, it could be REST, gRPC, your own protocols etc. Therefore, bringing REST-style specs into GraphQL isn't desirable.

You're using Extenstions correctly in your example, and your GraphQL client can make decisions based on the those bespoke codes but the GraphQL request itself is essentially successful.

That's just my opinion

The framework will return 422 on non-existing queries already, so it should be possible to also implement other returncodes when throwing errors. It's confusing to not have read lines in the browser console, if you always get 200.