Languages
[Edit]
EN

Express.js - handle exception

10 points
Created by:
Sujay
512

In this article, we would like to show how to handle exception in Express.js.

By exceptions handling we are able to:

  • send to user safe message when exception occurred hiding exception's sensitive information,
  • display in console details about occured exception.

Quick solution:

const express = require('express');

const app = express();

// app routes

// ...

app.get('/path/to/endpoint', (request, response, next) => {
    try {
        // Some logic here ...
    } catch (error) {
        return next(error);
    }
});

// ...

// error routes

app.use((error, request, response, next) => {
    response.status(500).send('Internal server error!');
    next(error);
});

// server running

app.listen(8080, () => console.log(`Server is listening on port 8080.`));

 

Reusable logic

In this section, you can find reusable functions that let to simplyfy your's application source code.

index.js file:

const express = require('express');

const {tryGet, tryPost, mapErrors} = require('./request');

const app = express();

// ...

tryGet(app, '/path/to/endpoint-1', async (request, response) => {
    // Some logic here ...
});

tryPost(app, '/path/to/endpoint-2', async (request, response) => {
    // Some logic here ...
});

// ...

mapErrors(app);

app.listen(8080, () => console.log(`Server is listening on port 8080.`));

 

request.js file:

exports.tryGet = (app, path, handler) => {
	return app.get(path, async (request, response, next) => {
		try {
			await handler(request, response);
		} catch (error) {
			return next(error);
		}
	});
};

exports.tryPost = (app, path, handler) => {
	return app.post(path, async (request, response, next) => {
		try {
			await handler(request, response);
		} catch (error) {
			return next(error);
		}
	});
};

exports.mapErrors = (app) => {
    app.use((error, request, response, next) => {
        console.error(`Method: ${request.method}, URL: ${request.protocol}://${request.hostname}${request.url}`);
        response
            .status(500)
            .json({
                result: false,
                message: 'Internal server error!'
            });
        next(error);
    });
};

 

Alternative titles

  1. Express.js - catch exception
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join