mm_os
Version:
MM_OS服务端架构,用于快速构建应用程序,支持网站建设、小程序后台、AI应用、物联网(IOT/AIOT)、游戏服务端等多种场景。
119 lines (101 loc) • 2.94 kB
JavaScript
// 导出错误处理中间件
module.exports = {
/**
* 初始化
* @param {object} adapter 适配器对象
*/
init(adapter) {
// 获取配置
this.config = { ...this.config, ...adapter.web.config};
},
/**
* 获取错误消息
* @private
* @param {object} config 配置对象
* @param {number} status 状态码
* @returns {string} 错误消息
*/
_getErrorMessage(config, status) {
if (config.error_codes && config.error_codes[status]) {
return config.error_codes[status];
}
return config.default_message || 'Internal Server Error';
},
/**
* 格式化错误信息
* @private
* @param {object} config 配置对象
* @param {Error} err 错误对象
* @returns {object} 格式化后的错误信息
*/
_formatError(config, err) {
let errorInfo = {
message: err.message,
status: err.status || err.statusCode || config.default_status,
stack: err.stack
};
if (err.code) {
errorInfo.code = err.code;
}
if (err.details) {
errorInfo.details = err.details;
}
if (err.name) {
errorInfo.name = err.name;
}
return errorInfo;
},
/**
* 处理错误
* @private
* @param {object} ctx Koa上下文
* @param {Error} err 错误对象
*/
async _handleError(ctx, err) {
// 记录错误日志到控制台
let error_info = this._formatError(this.config, err);
this.log('error', `Error occurred: ${err.message}`, error_info);
// 设置响应状态码
let status = err.status || err.status_code || this.config.default_status;
// 特殊错误处理:文件不存在错误返回404
if (err.code === 'ENOENT') {
status = 404;
}
ctx.status = status;
let message = err.message || this._getErrorMessage(this.config, status);
let error_response = $.ret.error(status, message);
// 如果配置允许,暴露堆栈信息(仅在开发环境使用)
if (this.config.expose_trace && err.stack) {
error_response.trace = err.stack;
}
// 添加额外的错误信息
if (err.code) {
error_response.error_code = err.code;
}
if (err.details) {
error_response.details = err.details;
}
// 设置响应体
ctx.body = error_response;
// 设置响应头
ctx.set('Content-Type', 'application/json');
},
/**
* 中间件主方法
* @param {object} ctx Koa上下文
* @param {Function} next 下一个中间件
* @returns {Promise<void>}
*/
async main(ctx, next) {
try {
await next();
// 处理404错误
if (ctx.status === 404 && !ctx.body) {
ctx.status = 404;
ctx.body = $.ret.error(404, 'Not Found');
}
} catch (error) {
await this._handleError(ctx, error);
}
}
};