Created
March 11, 2021 14:49
-
-
Save davixz/3843c1b51c52f1c03946e846b563af00 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Error Handling | |
The pattern of error return is: | |
{ | |
status: 500, | |
errors: [ | |
{ message: '......' }, //message will always be present | |
{ message: '......', id: '...' } //id may not always be present so check the existence before usage | |
{ message: '......', id: '...', stack_trace: '' } //its used for exception stack trace on dev | |
], | |
data: {}, //additional data we may want to return | |
data_raw: {} //this is the data returned without modifications, for example if you are communicating with external api, you can see how they return their errors here | |
} | |
-------- | |
if you see response.errors in the response it means something went wrong | |
-------- | |
data and data_raw may not always be present so check the existence before usage | |
-------- | |
You can use throw new Error() normally | |
The stack trace is preserved | |
throw new Error('My error message'); | |
If you dont catch the exception, this will translate into a single error in the response error list with the message you passed to Error() | |
This will produce a 500 status response | |
Additionaly You can do | |
throw new Error(JSON.stringify({ status: 400, message: 'My error message here' })); | |
throw new Error(JSON.stringify({ status: 400, id: 'my_error_id', message: 'My error message here' })); | |
We will set the response status for you as 400 | |
-------- | |
We have a hook to express response for requests that have method different from: GET, OPTIONS | |
If we see you returning errors but with response status like 200 we will change it to 400 | |
You can disable this behavior by setting a response header like so: | |
response.set('res-prevent-body-error-parsing', true); | |
For example if you are implementing some POST action that return a lot of data and you know if will not return errors | |
You can disable the behavior to gain performance |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment