123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
- 'use strict';
- const _ = require('lodash');
- module.exports = options => {
- return async function errorEmail(ctx, next) {
- try {
- await next();
- } catch (e) {
- let errcode = -1,
- errmsg = '服务发生错误',
- details;
- const emailData = {};
- const ekeys = Object.keys(e);
- if (ekeys.includes('errcode')) {
- // 人为抛出异常
- errcode = _.get(e, 'errcode');
- errmsg = _.get(e, 'errmsg');
- details = _.get(e, 'details');
- emailData.errmsg = errmsg;
- emailData.details = details;
- } else {
- // 由assert/参数判断抛出的
- errmsg = e.message;
- emailData.errmsg = e.stack;
- if (process.env.NODE_ENV === 'development') {
- details = e.stack;
- }
- }
- emailData.errcode = errcode;
- const request = ctx.request;
- const url = _.get(request, 'url');
- let body = _.get(request, 'body');
- if (body) body = JSON.stringify(body, null, 1);
- emailData.errmsg = `${url}\n${body}\n${emailData.errmsg}`;
- // console.log(emailData.errmsg);
- // 未定义的错误需要发邮件,定义的错误不需要
- if (!_.isNumber(e.errcode)) {
- // 非开发模式发送邮件
- if (process.env.NODE_ENV !== 'development') {
- ctx.service.util.email.errorEmail(emailData);
- }
- }
- ctx.fail(errcode, errmsg, details);
- }
- };
- };
|