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:
xxxxxxxxxx
1
const express = require('express');
2
3
const app = express();
4
5
// app routes
6
7
// ...
8
9
app.get('/path/to/endpoint', (request, response, next) => {
10
try {
11
// Some logic here ...
12
} catch (error) {
13
return next(error);
14
}
15
});
16
17
// ...
18
19
// error routes
20
21
app.use((error, request, response, next) => {
22
response.status(500).send('Internal server error!');
23
next(error);
24
});
25
26
// server running
27
28
app.listen(8080, () => console.log(`Server is listening on port 8080.`));
In this section, you can find reusable functions that let to simplyfy your's application source code.
index.js
file:
xxxxxxxxxx
1
const express = require('express');
2
3
const {tryGet, tryPost, mapErrors} = require('./request');
4
5
const app = express();
6
7
// ...
8
9
tryGet(app, '/path/to/endpoint-1', async (request, response) => {
10
// Some logic here ...
11
});
12
13
tryPost(app, '/path/to/endpoint-2', async (request, response) => {
14
// Some logic here ...
15
});
16
17
// ...
18
19
mapErrors(app);
20
21
app.listen(8080, () => console.log(`Server is listening on port 8080.`));
request.js
file:
xxxxxxxxxx
1
exports.tryGet = (app, path, handler) => {
2
return app.get(path, async (request, response, next) => {
3
try {
4
await handler(request, response);
5
} catch (error) {
6
return next(error);
7
}
8
});
9
};
10
11
exports.tryPost = (app, path, handler) => {
12
return app.post(path, async (request, response, next) => {
13
try {
14
await handler(request, response);
15
} catch (error) {
16
return next(error);
17
}
18
});
19
};
20
21
exports.mapErrors = (app) => {
22
app.use((error, request, response, next) => {
23
console.error(`Method: ${request.method}, URL: ${request.protocol}://${request.hostname}${request.url}`);
24
response
25
.status(500)
26
.json({
27
result: false,
28
message: 'Internal server error!'
29
});
30
next(error);
31
});
32
};