errorEmail.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. 'use strict';
  2. const _ = require('lodash');
  3. module.exports = options => {
  4. return async function errorEmail(ctx, next) {
  5. try {
  6. await next();
  7. } catch (e) {
  8. let errcode = -1,
  9. errmsg = '服务发生错误',
  10. details;
  11. const emailData = {};
  12. const ekeys = Object.keys(e);
  13. if (ekeys.includes('errcode')) {
  14. // 人为抛出异常
  15. errcode = _.get(e, 'errcode');
  16. errmsg = _.get(e, 'errmsg');
  17. details = _.get(e, 'details');
  18. emailData.errmsg = errmsg;
  19. emailData.details = details;
  20. } else {
  21. // 由assert/参数判断抛出的
  22. errmsg = e.message;
  23. emailData.errmsg = e.stack;
  24. if (process.env.NODE_ENV === 'development') {
  25. details = e.stack;
  26. }
  27. }
  28. emailData.errcode = errcode;
  29. const request = ctx.request;
  30. const url = _.get(request, 'url');
  31. let body = _.get(request, 'body');
  32. if (body) body = JSON.stringify(body, null, 1);
  33. emailData.errmsg = `${url}\n${body}\n${emailData.errmsg}`;
  34. // console.log(emailData.errmsg);
  35. // 未定义的错误需要发邮件,定义的错误不需要
  36. if (!_.isNumber(e.errcode)) {
  37. // 非开发模式发送邮件
  38. if (process.env.NODE_ENV !== 'development') {
  39. ctx.service.util.email.errorEmail(emailData);
  40. }
  41. }
  42. ctx.fail(errcode, errmsg, details);
  43. }
  44. };
  45. };