Here are a few ideas for error handling in an express app.
For all cases, you will want every route to handle any errors that can occur so that we can notify the caller and potentially do some logging.
Now, this can become quite tedious and repeated so we can pass the error to expresses default error handler!
This will cause express to pass the error out to the client, which in most cases is probably not what we want, so let's have a look at replacing the default error handling middleware.
This now gives us control to be able to add some default logging and return the status we want as well as and information we want to show to the consumer.
One really important thing to remember is to put the function after you define your route handlers! Or it won't catch the errors. (at the bottom of the file)
There are a few different types of things you might be doing in the routes so here are a few examples of how to pass the errors.
This one just handles synchronous code that throws errors.
In this case, we see an example of how to pass callback based errors.
And then moving into promises, as long as we make sure that we pass the error to next, the error handler middleware will be activated.
More on error handling strategies to come!
No comments:
Post a Comment