Error handling 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 middleware 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`);

});

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 errors 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 )=>{}

When an error is occurred in execution of request, the Express creates an Error objects and handover it to default error handling mechanism 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

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 )= > { } );



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

});

               

                               //write error handling middleware

                               app.use( (err , req , res , next )= > {

               console.log(err.stack);

               res.send(“something went wrong!!!!”);

 } );

                               //assign port number

                               app.listen(some port number here);

Rajesh T

Java Full stack & JavaScript Full Stack(MEAN ,MERN &Next.js) Developer & Instructor

4 年

Thank you anil

回复

要查看或添加评论,请登录

Rajesh T的更多文章

  • What is an API ?

    What is an API ?

    An API is a set of rules and protocols that allow different software applications to communicate with each other. Types…

    1 条评论
  • Redux vs Zustand for state management in React app

    Redux vs Zustand for state management in React app

    "A JS library for predictable and maintainable global state management" - Redux "A small, fast, and scalable bearbones…

    1 条评论
  • Simple state management in MEAN Application

    Simple state management in MEAN Application

    State management in Web apps is always challenging. Here, I have taken a simple e-learning app to demonstrate, state…

    1 条评论
  • Shallow copy vs Deep copy

    Shallow copy vs Deep copy

    Copy to an object can be created in many ways in JavaScript. Let us first understand difference between primitives and…

  • Units in CSS

    Units in CSS

    Absolute length units The absolute length units are fixed and a length expressed in any of these will appear as exactly…

  • Promises in JavaScript

    Promises in JavaScript

    The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting…

  • Callbacks in JavaScript

    Callbacks in JavaScript

    Most of us feel confusion while learning about asynchronous behavior of JavaScript. In this article i tried to explain…

  • Storing images in MEAN stack application using "Cloudinary"

    Storing images in MEAN stack application using "Cloudinary"

    Saving images and videos of a web application is always challenging, because, performance of application matters.We…

    2 条评论
  • Connecting Angular application with Nodejs backend

    Connecting Angular application with Nodejs backend

    In this article, i will explain ,how to connect Angular Application with Nodejs backend. When we create a new angular…

  • Token based Authentication in ExpressJS Application

    Token based Authentication in ExpressJS Application

    HTTP is a stateless protocol. That means ,it cannot maintain state of previous requests.

社区洞察

其他会员也浏览了