Where to place error handler middleware in Express?

Phi

New Member
#1
I've just finished my middleware handler error.js as follow. I intend send error message based on http code.
Mã:
var HttpStatus = require('http-status-codes');

function errorHandler(err, req, res) {
    // Set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // Log error
    console.error(err.stack);

    // Render the error page
    res.status(err.status || 500);

    // Default error message by HTTP code
    res.render('error', {
        title: HttpStatus.getStatusText(err.status),
        message: HttpStatus.getStatusText(err.status)
    });
};
Now, I don't know where to place this middleware in my app.js. Should I place it after or before module load?
Mã:
// Create express app
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

// Middlewares
app.use(logger('combined'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use('/static', express.static(path.join(__dirname, 'public')));

// Load routers
app.use('/', indexRouter);
app.use('/users', usersRouter);
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top