EN
Express.js - handle exception
10
points
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);
});
};