-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathapp.ts
More file actions
164 lines (145 loc) · 4.68 KB
/
app.ts
File metadata and controls
164 lines (145 loc) · 4.68 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
import fs from 'node:fs';
import http from 'node:http';
import type { ILifecycleBoot, Application, Context } from 'egg';
import type { OnerrorConfig } from './config/config.default.ts';
import { ErrorView } from './lib/error_view.ts';
import { onerror, type OnerrorOptions, type OnerrorError } from './lib/onerror.ts';
import { isProd, detectStatus, detectErrorMessage, accepts } from './lib/utils.ts';
export interface OnerrorErrorWithCode extends OnerrorError {
code?: string;
type?: string;
errors?: any[];
}
export default class Boot implements ILifecycleBoot {
private app: Application;
constructor(app: Application) {
this.app = app;
}
async didLoad(): Promise<void> {
// logging error
const config = this.app.config.onerror;
const viewTemplate = config.templatePath
? fs.readFileSync(config.templatePath, 'utf8')
: (await import('./lib/onerror_page.ts')).ONERROR_PAGE_TEMPLATE;
const app = this.app;
app.on('error', (err, ctx) => {
if (!ctx) {
ctx = app.currentContext || app.createAnonymousContext();
}
if (config.appErrorFilter && !config.appErrorFilter(err, ctx)) return;
const status = detectStatus(err);
// 5xx
if (status >= 500) {
try {
ctx.logger.error(err);
} catch (ex) {
app.logger.error(err);
app.logger.error(ex);
}
return;
}
// 4xx
try {
ctx.logger.warn(err);
} catch (ex) {
app.logger.warn(err);
app.logger.error(ex);
}
});
const errorOptions: OnerrorOptions = {
// support customize accepts function
accepts(this: Context) {
const fn = config.accepts || accepts;
return fn(this as any);
},
html(err, ctx: Context) {
const status = detectStatus(err);
const errorPageUrl =
typeof config.errorPageUrl === 'function' ? config.errorPageUrl(err, ctx) : config.errorPageUrl;
// keep the real response status
ctx.realStatus = status;
// don't respond any error message in production env
if (isProd(app)) {
// 5xx
if (status >= 500) {
if (errorPageUrl) {
const statusQuery = (errorPageUrl.indexOf('?') > 0 ? '&' : '?') + `real_status=${status}`;
return ctx.redirect(errorPageUrl + statusQuery);
}
ctx.status = 500;
ctx.body = `<h2>Internal Server Error, real status: ${status}</h2>`;
return;
}
// 4xx
ctx.status = status;
ctx.body = `<h2>${status} ${http.STATUS_CODES[status]}</h2>`;
return;
}
// show simple error format for unittest
if (app.config.env === 'unittest') {
ctx.status = status;
ctx.body = `${err.name}: ${err.message}\n${err.stack}`;
return;
}
const errorView = new ErrorView(ctx, err, viewTemplate);
ctx.body = errorView.toHTML();
},
json(err: OnerrorErrorWithCode, ctx: Context) {
const status = detectStatus(err);
let errorJson: Record<string, any> = {};
ctx.status = status;
const code = err.code ?? err.type;
const message = detectErrorMessage(ctx, err);
if (isProd(app)) {
// 5xx server side error
if (status >= 500) {
errorJson = {
code,
// don't respond any error message in production env
message: http.STATUS_CODES[status],
};
} else {
// 4xx client side error
// addition `errors`
errorJson = {
code,
message,
errors: err.errors,
};
}
} else {
errorJson = {
code,
message,
errors: err.errors,
};
if (status >= 500) {
// provide detail error stack in local env
errorJson.stack = err.stack;
errorJson.name = err.name;
for (const key in err) {
if (!errorJson[key]) {
errorJson[key] = (err as any)[key];
}
}
}
}
ctx.body = errorJson;
},
js(err, ctx: Context) {
errorOptions.json!.call(ctx, err, ctx);
if (typeof ctx.createJsonpBody === 'function') {
ctx.createJsonpBody(ctx.body);
}
},
};
// support customize error response
const keys: (keyof OnerrorConfig)[] = ['all', 'html', 'json', 'text', 'js'];
for (const type of keys) {
if (config[type]) {
Reflect.set(errorOptions, type, config[type]);
}
}
onerror(app, errorOptions);
}
}