DEV Community

Rajesh T
Rajesh T

Posted on

Handling Errors in Express Application

Error Handling refers to how Express catches and processes errors that occur both synchronously and asynchronously. Express comes with a default error handler so you don’t need to write your own to get started.

An error can be occurred in an Express application in the following two cases.
1.When requested route is not found in server
2.When the request handling middle ware generates an error.

Handling unavailable routes

Express Application creates a routing table in the order of route handlers in the application. When a client makes a request,It can start comparing the request handlers in the order of they derived.
If no match found,then it returns an HTML response with error message in it. We can handle this error by adding a middleware as last one in the application.

app.use( (req, res, next) = > {
res.send(`path  ${ req.url } of type request ${ req.method }is not found`);
Enter fullscreen mode Exit fullscreen mode

});

This middleware function can execute for every client’s request. So , by placing this as last one,we can make it respond only for unavailable paths.

Handling error of request handling middlewares

Whenever an error is occurred ,the default Error handling middleware of express can deal with that.
The default error handling middleware take four objects like below.

    (error, request , response , next )=>{}
Enter fullscreen mode Exit fullscreen mode

When an error is occurred in execution of request, the Express creates an Error objects and handover it to default error handling mechanish by suspending the execution rest of code in that request handler.
One can throw an Error object to that default error handler by using

            let err=new Error(“error message”);
    next(err);  //this will call error handling middleware
Enter fullscreen mode Exit fullscreen mode

Note: next() will call next middleware in the list where as next(err) will call error handling middleware

Now add the following error handling middleware as last one in the list and just above list() method.

        app.use( (err , req , res , next )= > { } ); 
Enter fullscreen mode Exit fullscreen mode

So the final order of route handlers in express app should like below

    //write all request handlers
    //write middleware to deal with unavailable paths
        app.use( (req, res, next) = > {
res.send(`path  ${ req.url } of type request ${ req.method }is not found`);
Enter fullscreen mode Exit fullscreen mode

});

    //write error handling middleware
    app.use( (err , req , res , next )= > {
console.log(err.stack);
res.send(“something went wrong!!!!”);
Enter fullscreen mode Exit fullscreen mode

} );
//assign port number
app.listen(some port number here);

Top comments (0)