Contrary to REST, GraphQL does not use Status Coe to differentiate a successful result from an exception.
In Rest,
400 : bad request (something like invalid inputs)
401 or 405 : unauthorized (need authentication) or forbidden(insufficient permission)
404 : resource not found
500 : internal server error
…
In GraphQL, however we mange errors in a different way.
GraphQL Default Error Handling
- all requests must go to a single endpoint
POST {{Dentbird_API_Gateway}}/api/v2/graphql
- always return 200 OK Status Code, even in case of error !
- When server is not available → you’ll get 5xx error
This is actually a common practice, but it is not mandatory.
You could send GraphQL responses with different Status Codes. It would however need to be implemented at the server level and not at the operation resolvers level.
As an example, you can check out graphql-helix implementation of some error cases' responses with different Status Codes
- 400 for GraphQL syntax or validation error,
- 405 when using not allowed HTTP method (e.g. GET for mutations or using anything else than POST or GET for queries).
- The standard error handling mechanism is returning a JSON
- data : key which contains the data corresponding to the GraphQL operation invoked
- errors : key which contains an array of errors returns by the server, with a message and location
- the problem of standard error handling
- not easily parseable → human friendly
- not typed → we can add more information
- an error code and other field → but those are not part of the schema
- not self-documented
- self-documented?
- self-documenting code is code that is written in a way that is easy to understand and that conveys its purpose and function without the need for extensive documentation.
- self-documented?
Error Categories
- error
- Internal Server Error and Bad Gateway, something went wrong in servicing the request. So, these are definitely errors.
- results
- cases like Deleted User, Unavailable in Country, and Suspended User, nothing went wrong at all.
request to our GraphQL server → our server will make subsequent calls to our backends/services
If one of our services throws an exception, we'll get a HTTP 500 (or equivalent) back, and something like "Server Error" will end up in our errors array.
Modeling Results in the GraphQL Schema
- list all the possible response
- customize what each result look like depending on what Result Type we have
Error Handling with GraphQL Union Types
https://www.youtube.com/watch?v=AJOh-0Gdvt8
'개발' 카테고리의 다른 글
NestJs - Mircoservices (2) | 2023.11.08 |
---|---|
How to do a code review (0) | 2023.11.03 |
[개발] 주니어 개발자로 내가 자주하는 실수 및 경험 - 기록편 (0) | 2023.05.31 |
[슬기로운 나름의 신입 사원 생활] IDS 2023 - 출국편 : 내가 해외 출장을 떠나다! (0) | 2023.03.31 |
[한국관광공사] 2022 관광데이터활용 공모전 최우수상 수상 (0) | 2022.10.10 |