-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
46 lines (40 loc) · 1.07 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
const HTTP_STATUS = require('http-status');
const { NODE_ENV } = process.env;
const finalHandler = () => async (ctx, next) => {
try {
await next();
// Handle 404 upstream.
const status = ctx.response.status || 404;
if (status === 404) ctx.throw(404);
} catch (error) {
if (error.status) {
ctx.response.status = error.status;
} else if (error.name === 'ValidationError') {
ctx.response.status = 400;
ctx.response.body = {
error: {
message: error.details
? error.details.map((d) => d.message).join('\n')
: null,
},
};
} else {
ctx.response.status = 500;
if (NODE_ENV === 'development') {
ctx.response.body = { error };
}
}
if (!ctx.response.body) {
ctx.response.body = {
error: {
message:
error.message && ctx.response.status < 500
? error.message
: HTTP_STATUS[ctx.response.status],
},
};
}
ctx.app.emit('error', error, ctx);
}
};
module.exports = finalHandler;