Use error handler or extend objecto response in express

0

Good morning, I am doing a REST API project using Express and with the intention of refactoring the code to return the client an error response I do not know which of the following options is more efficient:

Use a bug handler as specified in the Express guide.

app.use((err,req,res,next)=>{
  console.log('ERROR HANDLER: ', err);
  res.status(err.status || 500).send(err); //custom error
});

so that in each catch of a Promise ...

function(req, res, next) {
 Promise
 .then( ... ) // throw error
 .catch(next)
}

Or extend the response object as follows:

express.response.error_ = function(err){
  this.status(err.status || 500).send(err);
}

in this way I can execute ...

function(req, res, next) {
 Promise
 .then( ... ) // throw error
 .catch(res.error_)
}

Which of these is the best option?

Thank you very much in advance and greetings.

    
asked by DiDream 24.10.2017 в 23:37
source

2 answers

0

I think it would be better to use the first form, as indicated by the Express guide, since it is easier to do a test directly from this handler without relying on express just mocking the objects and also have more architecture " clean ", for example you can have your handler in this way in a file customErrorHandler.js:

//middlewares/customErrorHanlder.js
module.exports = function customErrorHandler(err,req,res){
    //Procesamiento del error
}

//app.js
var customErrorHandler = require("./middlewares/customErrorHandler")
var app = require('express')();

app.get('/', function(req, res,next){
 //Procesamiento get
 next(new Error("error"))
});


app.use(customErrorHandler);

app.listen(3000);
    
answered by 25.10.2017 / 20:34
source
0

The best way is to create an error handler at the end of the entire document, that is, behind all the routes. In these routes you must pass a new error by next () and that error will be picked up by the error handler.

var express = require('express');
var app = express();

app.get('/', function(req, res){
    // Creamos el error y lo pasamos al manejador 
    // Acuérdate de utilizar 'var' ya que necesitamos un scope global 
    var err = new Error("Mensaje de error");
    next(err);
});

/*
 * Otras rutas GET, POST, etc...
 */

//El error es 
app.use(function(err, req, res, next) {
    res.status(500);
    res.send("Oops, something went wrong.")
});

app.listen(3000);
    
answered by 25.10.2017 в 12:15