error_handler.js 1.7 KB

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