error-handle.js
1.26 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
*
* @author: jiangfeng<jeff.jiang@yoho.cn>
* @date: 16/8/3
*/
'use strict';
async function errorHandle(err, ctx) {
let code = err ? 500 : ctx.response.status;
let message = err ? err.toString() : ctx.response.message;
switch (ctx.accepts('json', 'html', 'text')) {
case 'json':
ctx.body = {
code: code,
message: message
};
break;
case 'html':
await ctx.render('action/500', {error: err.stack || err});
break;
default:
break;
}
}
function statusHandle(ctx) {
let status = ctx.response.status;
if (status === 404) {
switch (ctx.accepts('json', 'html', 'text')) {
case 'json':
ctx.body = {
code: status
};
break;
case 'html':
ctx.redirect('/' + status);
break;
default:
break;
}
}
}
module.exports = function(app) {
return async function(ctx, next) {
try {
await next();
statusHandle(ctx);
} catch (err) {
console.error(err.stack || err);
await errorHandle(err, ctx);
}
};
}