3 ms·
Great write-up. One aspect of GraphQL that I've found difficult is communicating errors to consumers in a developer-friendly way. What is the best way for Graph
by geekjock 8y ago
Great write-up. One aspect of GraphQL that I've found difficult is communicating errors to consumers in a developer-friendly way. What is the best way for GraphQL server to communicate to the client the equivalent of HTTP status codes 500, 404, etc?
The approach I recently implemented was to add a "type" or "code" property with standardized values to error objects in the GraphQL response (similar to error codes in Stripes REST API [0]). The client can then check those "errors" objects for specific codes and behave accordingly.
[0] https://stripe.com/docs/error-codes https://stripe.com/docs/error-codes
- joshribakoff 8y agoThis is in the docs. https://graphql.org/learn/serving-over-http/ https://graphql.org/learn/serving-over-http/ > [a] query might result in some data and some errors, and those should be returned in a JSON object of the form {data: {}, errors: [] } Also checkout https://github.com/kadirahq/graphql-errors https://github.com/kadirahq/graphql-errors which exposes a standard `path` field for each error, so the client has a standard way to know which part of the query resulted in an error. If a mutation fails, for example a bank withdrawal fails because of insufficient funds, that is not necessarily an "error". To quote "code complete": > Exceptions should be reserved for what's truly exceptional. I'd send a mutation like this: withdrawFunds($amount: 100, $currency: "USD") { didSucceed didOverdraft canRetry } The client can control exactly which field(s) to request, or simply fire & forget if it does not care if the transaction went through. If you change your mind later, you can add & deprecate fields, in the true spirit of graphQL. In the case you shove arbitrary error codes in strings, you lose the benefits graphQL brings, like tracking usage of a field, self documenting & introspection, solving for over/under fetching, and the ability to revise these codes without versioning your mutations.