With express middleware there is a default error handling middleware that works okay for simple projects, but there will come a time now and then where it might be necessary to write custom error handling middleware. When writing an error handling middleware for express the process of doing so is more or less the same as writing any other middleware in express only there are four arguments to be aware of rather than the usual three.
If a middleware throws an error that is not the result of some kind of async type action, then express will just handle the error. The default error handler will fire, unless a custom error handler middleware is defined.
To define an error handling middleware in express just do so in the same way as any other middleware, but with just one little difference. The first argument in the function will be for the error object, and not the request object.
When it comes to anything async that is happening in a express middleware that might result in an error, the error should be passed as an argument to the next method.