Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I handle errors in express globally without using try and catch in my controllers

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.

like image 678
Oto-Obong Eshiett Avatar asked Oct 19 '25 22:10

Oto-Obong Eshiett


1 Answers

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);
like image 190
Owl Avatar answered Oct 21 '25 14:10

Owl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!