/**
* 自动加载全部路由文件并注册
*/
static initRouters() {
// 绝对路径
const routesDirectory = `${process.cwd()}/src/routes`;
requireDirectory(module, routesDirectory, {
visit: whenLoadModule
});
/**
* 当每个模块被加载的时候会触发调用
* @param {obj} obj 路由实例
*/
function whenLoadModule(obj) {
if (obj instanceof Router) {
InitApp.app.use(obj.routes(), obj.allowedMethods());
}
}
}
const catchError = async (ctx, next) => {
try {
await next();
} catch (error) {
const isHttpException = error instanceof HttpException;
console.error(error);
// 开发环境下直接抛出
if (isDev && !isHttpException) {
throw error;
}
// 已知异常
if (isHttpException) {
ctx.body = {
msg: error.msg,
request: `${ctx.method} ${ctx.path}`
};
ctx.status = error.code;
// 未知异常
} else {
ctx.body = {
msg: "未知错误!",
request: `${ctx.method} ${ctx.path}`
};
ctx.status = 500;
}
}
};