You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
58 lines
1.8 KiB
58 lines
1.8 KiB
const Koa = require('koa');
|
|
const app = new Koa();
|
|
require('console-color-mr'); //颜色模块
|
|
const koaBody = require('koa-body'); //处理post请求参数
|
|
|
|
|
|
app.use(koaBody({
|
|
multipart: true, // 支持文件上传
|
|
}));
|
|
|
|
// 配置解析请求中间件
|
|
const autoUpdateRouter = require('./routers/auto/AutoUpdateRouter');
|
|
app.use(autoUpdateRouter.routes());
|
|
app.use(autoUpdateRouter.allowedMethods());
|
|
|
|
// 字符串转换
|
|
const json = require('koa-json');
|
|
app.use(json());
|
|
// 捕获错误logger 记录
|
|
const logsUtil = require('./utils/LogUtil');
|
|
//环境配置
|
|
const config = require('./config/EnvApplication/'+ process.env.NODE_ENV);
|
|
|
|
// 错误处理中间件(注意:这不会捕获由 Koa 抛出的 'error' 事件)
|
|
app.use(async (ctx, next) => {
|
|
try {
|
|
await next();
|
|
// 如果 Koa 没有找到任何路由来处理请求,它将自动设置 ctx.status 为 404
|
|
if (ctx.status === 404) {
|
|
ctx.status = 404;
|
|
ctx.body = {
|
|
error: 'Not Found',
|
|
code: 404,
|
|
message: 'The requested resource could not be found.'
|
|
};
|
|
}
|
|
} catch (err) {
|
|
// 这里捕获在路由处理函数中抛出的错误
|
|
logsUtil.logError(ctx, err);
|
|
ctx.status = 500;
|
|
ctx.body = {
|
|
error: 'Internal Server Error',
|
|
code: 500,
|
|
message: 'An unexpected error occurred on the server.'
|
|
};
|
|
}
|
|
});
|
|
// 捕获未被处理的错误(如异步错误或中间件外的错误)
|
|
app.on('error', (err, ctx) => {
|
|
logsUtil.logError(ctx, err);
|
|
// 注意:此时响应可能已经被发送到客户端,所以你不能修改 ctx.body 或 ctx.status
|
|
// 你可以在这里做其他清理工作,比如关闭数据库连接等
|
|
});
|
|
|
|
// 启动服务器
|
|
app.listen(config.port, () => {
|
|
console.info(`Server is running on port ${config.port} in ${process.env.NODE_ENV} mode`);
|
|
});
|