Skip to content

Commit 0df41dd

Browse files
committed
add error log
1 parent 01c0aef commit 0df41dd

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

packages/server/service/server.ts

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import { Context } from 'cordis';
22
import proxy from 'koa-proxies';
3-
import { ForbiddenError, WebService } from '@hydrooj/framework';
3+
import { ForbiddenError, HydroError, NotFoundError, UserFacingError, WebService } from '@hydrooj/framework';
44
import { config } from '../config';
55
import { randomstring } from '../utils';
6+
import { errorMessage } from '@hydrooj/utils';
67
export * from '@hydrooj/framework/decorators';
78

89
export async function apply(pluginContext: Context) {
@@ -56,5 +57,35 @@ export async function apply(pluginContext: Context) {
5657
},
5758
})(ctx, next);
5859
});
60+
server.httpHandlerMixin({
61+
async onerror(error: HydroError) {
62+
error.msg ||= () => error.message;
63+
if (error instanceof UserFacingError && !process.env.DEV) error.stack = '';
64+
if (!(error instanceof NotFoundError) && !('nolog' in error)) {
65+
// eslint-disable-next-line max-len
66+
console.error(`${this.request.method}: ${this.request.path}`, error.msg(), error.params);
67+
if (error.stack) console.error(error.stack);
68+
}
69+
this.response.status = error instanceof UserFacingError ? error.code : 500;
70+
this.response.body = {
71+
UserFacingError,
72+
error: { message: error.msg(), params: error.params, stack: errorMessage(error.stack || '') },
73+
};
74+
},
75+
});
76+
server.wsHandlerMixin({
77+
async onerror(err: HydroError) {
78+
console.error(`Path:${this.request.path}`);
79+
console.error(err);
80+
if (err instanceof UserFacingError) err.stack = this.request.path;
81+
this.send({
82+
error: {
83+
name: err.name,
84+
params: err.params || [],
85+
},
86+
});
87+
this.close(4000, err.toString());
88+
},
89+
});
5990
});
6091
}

0 commit comments

Comments
 (0)