leangen / graphql-spqr

Build a GraphQL service in seconds
Apache License 2.0
1.09k stars 181 forks source link

Best way to error handling #477

Open yashb042 opened 11 months ago

yashb042 commented 11 months ago

In a normal API server, we will get both success and error responses. If I have a response POJO like this:

public class FinalChannelResponse  {
    public List<InvList> inv;
    public Integer sort;
    public Integer sortOrder;
}

and a corresponding error response POJO like this :

public class ErrorResponse  {
    public String msg;
}

How do I incorporate both the responses in an API call. For example, I want to get the channel response, I call the graphQL query as :

getChannel(){
__typename
inv
sort
sortOrder
}

Now, if I get an error in the code, I should be getting the errorResponse instead. So my actual graphQL query should look like (not exactly correct):

getChannel(){
... on FinalChannelResponse{
__typename
inv
sort
sortOrder
}
... on ErrorResponse{
msg
}
}

For this to happen, I should have a common interface in my resolver response which is implemented by both FinalChannelResponse and ErrorResponse. So I created, ISearchResponse as

public interface ISearchResponse{
}

Now both my FinalChannelResponse and ErrorResponse implements this interface, and my resolver function returns ISearchResponse. I am getting the following exception when running this.

Exception in thread "main" graphql.schema.validation.InvalidSchemaException: invalid schema:
"ISearchResponse" must define one or more fields.
    at graphql.schema.GraphQLSchema$Builder.validateSchema(GraphQLSchema.java:945)
    at graphql.schema.GraphQLSchema$Builder.buildImpl(GraphQLSchema.java:939)
    at graphql.schema.GraphQLSchema$Builder.build(GraphQLSchema.java:904)
    at io.leangen.graphql.GraphQLSchemaGenerator.generateExecutable(GraphQLSchemaGenerator.java:993)
    at io.leangen.graphql.GraphQLSchemaGenerator.generate(GraphQLSchemaGenerator.java:936)
    at io.dropwizard.cli.EnvironmentCommand.run(EnvironmentCommand.java:43)
    at io.dropwizard.cli.ConfiguredCommand.run(ConfiguredCommand.java:85)
    at io.dropwizard.cli.Cli.run(Cli.java:75)
    at io.dropwizard.Application.run(Application.java:79)

@kaqqao @BaldyLocks Any solutions on this, is the approach correct?

yashb042 commented 11 months ago

Basically, I want to implement interfaces as mentioned in this article - https://sachee.medium.com/200-ok-error-handling-in-graphql-7ec869aec9bc