error.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. const mailSend = require('../util/mailSend');
  2. const sys = require('../config/sys');
  3. let api, adminMail;
  4. class OwnError extends Error {
  5. constructor(msg = '', code = 400, additional = undefined) {
  6. super();
  7. this.msg = msg;
  8. this.code = code;
  9. this.additional = additional;
  10. }
  11. }
  12. function err(msg, code, additional) {
  13. throw (new OwnError(msg, code, additional));
  14. }
  15. async function error(ctx, next) {
  16. try {
  17. ctx[api] = err;
  18. await next()
  19. } catch (e) {
  20. let body;
  21. if (e instanceof OwnError) {
  22. ctx.status = e.code
  23. body = {
  24. msg: e.msg,
  25. content: e.additional
  26. }
  27. } else {
  28. ctx.status = 500
  29. body = { code: 500, msg: '系统发生错误,请稍后再试!' };
  30. if (!sys.debug && adminMail) {
  31. await mailSend({
  32. to: adminMail,
  33. subject: '4维时代公众号SDK平台错误提醒',
  34. html: `<h1>${e.message}</h1><div>${e.stack ? e.stack.replace(/\n/ig, '<br>') : e}</div>`
  35. });
  36. } else {
  37. throw e;
  38. }
  39. }
  40. ctx.body = body;
  41. }
  42. }
  43. function init(_api = 'error', _adminMail) {
  44. api = _api;
  45. adminMail = _adminMail;
  46. return error;
  47. }
  48. module.exports = exports = init;