5.3 Unit 5 Error Handling
5.3 Unit 5 Error Handling
Error Handling
• Error handling in Express is done using middleware.
• But this middleware has special properties.
• The error handling middleware are defined in the same way as other middleware
functions, except that error-handling functions MUST have four arguments
instead of three – err, req, res, next.
• For example, to send a response on any error, we can use:
2
Error Handling
• Till now we were handling errors in the routes itself.
• The error handling middleware allows us to separate our error logic and send
responses accordingly.
• The next() method we discussed in middleware takes us to next middleware/route
handler.
3
Error Handling
• For error handling, we have the next(err) function.
• A call to this function skips all middleware and matches us to the next error handler
for that route.
• Let us understand this through an example.
4
Error Handling
• This error handling middleware can be strategically placed after routes or contain
conditions to detect error types and respond to the clients accordingly.
• The above program will display the following output.
5
Debugging
• Express uses the Debug module to internally log information about route matching,
middleware functions, application mode, etc.
• To see all internal logs used in Express, set the DEBUG environment variable
to Express:* when starting the app:
6
Debugging
• The following output will be displayed.
7
Debugging
• These logs are very helpful when a component of your app is not functioning right.
• This verbose output might be a little overwhelming.
• You can also restrict the DEBUG variable to specific area to be logged.
• For example, if you wish to restrict the logger to application and router, you can use
the following code.