This commit is contained in:
艾贤凌
2026-03-16 12:05:55 +08:00
parent af3a7c83e8
commit 6d4a72161f
33 changed files with 5671 additions and 178 deletions

View File

@@ -0,0 +1,22 @@
import * as log4js from '../../log4js.js'
/**
* 统一错误处理中间件
* 捕获所有未处理异常,规范化错误响应格式,避免泄露内部错误信息
*/
export default async function errorHandler(ctx, next) {
try {
await next()
} catch (err) {
log4js.koa.error(`[${ctx.method}] ${ctx.path}${err.message}`, err.stack || '')
// 已知业务错误(主动 throw new Error直接返回消息
if (err.status) {
ctx.status = err.status
ctx.body = { code: err.status, message: err.message || '请求错误' }
} else {
ctx.status = 500
ctx.body = { code: 500, message: '服务器内部错误,请稍后再试!' }
}
}
}