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);

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

Best practices for optimal infrastructure performance with Magento

Running a Magento store? Struggling with performance bottlenecks? Join us and get actionable insights and real-world strategies to keep your store fast and reliable.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️