Expressjs - Error Handling with Middleware

I am creating an API (using Expressjs v4), and I usually looked for errors along the route, rather than using middleware. For instance:

router.use('/', function(req, res, next) { ... if (err) return res.status(500).send({type: "serverError", message: "Something has gone wrong on our end."}); } 

Now I understand that middleware is the "way". I saw pretty limited documentation on the Expressjs website: http://expressjs.com/guide/error-handling.html , but still not sure about some things.

I added in server.js :

 function errorHandler(err, req, res, next) { } 

but how can I handle various types of errors (400 404 500, etc.)?

I find that I write 3 lines of code every time an error occurs:

 //A route var err = new Error(); err.status = 404; return next(err); 

and I can access the status using:

 function errorHandler(err, req, res, next) { console.log(err.status); if(err.status == "400") //do something else //etc etc } 

Of course, is there an easier way? Did I miss something?

+5
source share
2 answers

You must create your own type of error that will allow you to provide all the information necessary to resolve the error.

 var util = require('util'); function HttpError(message, statusCode){ this.message = message; this.statusCode = statusCode; this.stack = (new Error()).stack; } util.inherits(Error, HttpError); module.exports = HttpError; 

Then include your new error object in your code and use it as

 next(new HttpError('Not Found', 404)); 

Or you can go crazy and implement an error type for each response code by pre-filling the statusCode part.

Link: What is a good way to extend the error in JavaScript?

+2
source

Instead of manually creating an error, you can delegate this error, as shown below.

 return next(err); 

And your mistake will go deep into all the routes defined until it finds routes with a signature.

 app.use(function (err, req, res, next) { }); 

You can see the err argument in the above route.

Ideally, you can use below two methods for the DEVELOPMENT and PRODUCTION environment.

 if (process.env.NODE_ENV === 'development') { app.use(function (err, req, res, next) { res.status(err.status || 500); logger.log('info', err.message + " expected URL was " + req.url); res.status(err.status).send(err.status, { message: err.message, error : err }); }); } app.use(function (err, req, res, next) { res.status(err.status || 500); logger.log('error', err.message + " expected URL was " + req.url); res.status(err.status).send(err.status, { message: err.message, error : {} }); }); 

You can capture the actual bug settlement there.

+2
source

Source: https://habr.com/ru/post/1208243/


All Articles