- ExpressJS - Resources
- ExpressJS - Best Practices
- ExpressJS - Debugging
- ExpressJS - Error handling
- ExpressJS - Scaffolding
- ExpressJS - RESTful APIs
- ExpressJS - Authentication
- ExpressJS - Sessions
- ExpressJS - Cookies
- ExpressJS - Database
- ExpressJS - Form Data
- ExpressJS - Static Files
- ExpressJS - Templating
- ExpressJS - Middleware
- ExpressJS - URL Building
- ExpressJS - HTTP Methods
- ExpressJS - Routing
- ExpressJS - Hello World
- ExpressJS - Environment
- ExpressJS - Overview
- ExpressJS - Home
ExpressJS Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
ExpressJS - Error Handpng
Error handpng in Express is done using middleware. But this middleware has special properties. The error handpng middleware are defined in the same way as other middleware functions, except that error-handpng functions MUST have four arguments instead of three – err, req, res, next. For example, to send a response on any error, we can use −
app.use(function(err, req, res, next) { console.error(err.stack); res.status(500).send( Something broke! ); });
Till now we were handpng errors in the routes itself. The error handpng 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.
For error handpng, 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.
var express = require( express ); var app = express(); app.get( / , function(req, res){ //Create an error and pass it to the next function var err = new Error("Something went wrong"); next(err); }); /* * other route handlers and middleware here * .... */ //An error handpng middleware app.use(function(err, req, res, next) { res.status(500); res.send("Oops, something went wrong.") }); app.psten(3000);
This error handpng middleware can be strategically placed after routes or contain conditions to detect error types and respond to the cpents accordingly. The above program will display the following output.
Advertisements