2

I am fairly new to express and want to know if there exists a global error catcher. I am working on an already existing code with all the controllers created and it would be rookie to implement try and catch in all the controllers. I need a global error catcher to that detects breaks in the code and responds to the client. is there an existing library for that or an existing code implementation.

1 Answers1

6

If your controllers aren't asynchronous, you can simply add error handler after you registered all of your route

const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
    throw new Error('Something went wrong');
});

// Add more routes here

// Error handler
app.use(function (err, req, res, next) {
    // All errors from non-async route above will be handled here
    res.status(500).send(err.message)
});

app.listen(port);

If your controllers are asynchronous, you need to add a custom middleware to your controller to handle async error. The middleware example is taken from this answer

const express = require('express');
const app = express();
const port = 3000;

// Error handler middleware for async controller
const asyncHandler = fn => (req, res, next) => {
    return Promise
        .resolve(fn(req, res, next))
        .catch(next);
};

app.get('/', asyncHandler(async (req, res) => {
    throw new Error("Something went wrong!");
}));

// Add more routes here

// Error handler
app.use(function (err, req, res, next) {
    // All errors from async & non-async route above will be handled here
    res.status(500).send(err.message)
})

app.listen(port);
Owl
  • 5,106
  • 2
  • 9
  • 23