123456789101112131415161718192021222324252627282930313233343536373839 |
- 'use strict';
- module.exports = (option, app) => {
- return async function(ctx, next) {
- try {
- ctx.logger.info('请求地址', ctx.request.url);
- // 记录以下字段
- // header:
- // { host: '10.16.5.155:7001', 主机
- // connection: 'keep-alive', 连接
- // accept: 'application/json, text/plain, */*', 请求类型
- // origin: 'http://10.16.5.155:8080', 来源
- // sessionid: '33b4e3c0f5fb11e9ba2cb3d872c3b122', sessionId
- // 'user-agent': 来源设备
- // 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
- // referer: 'http://10.16.5.155:8080/', 来源
- // 'accept-encoding': 'gzip, deflate', 开始压缩
- // 'accept-language': 'zh-CN,zh;q=0.9' 语言} }
- await next();
- } catch (err) {
- // 所有的异常都在 app 上触发一个 error 事件,框架会记录一条错误日志
- app.emit('error', err, this);
- const status = err.status || 500;
- // 生产环境时 500 错误的详细错误内容不返回给客户端,因为可能包含敏感信息
- const error = status === 500 && app.config.env === 'prod' ?
- 'Internal Server Error' :
- err.message;
- // 从 error 对象上读出各个属性,设置到响应中
- ctx.body = {
- code: status, // 服务端自身的处理逻辑错误(包含框架错误500 及 自定义业务逻辑错误533开始 ) 客户端请求参数导致的错误(4xx开始),设置不同的状态码
- msg: error,
- };
- if (status === 422) {
- ctx.body.errors = err.errors;
- }
- ctx.status = 200;
- }
- };
- };
|