error-handler.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. 'use strict';
  2. const { AssertionError } = require('assert');
  3. const { BusinessError, ErrorCode } = require('naf-core').Error;
  4. module.exports = options => {
  5. return async function(ctx, next) {
  6. try {
  7. await next();
  8. } catch (err) {
  9. if (err instanceof BusinessError /* && ctx.acceptJSON */) {
  10. // 业务错误
  11. let res = { errcode: err.errcode, errmsg: err.errmsg };
  12. if (options.details) {
  13. res = { errcode: err.errcode, errmsg: err.errmsg, details: err.details };
  14. }
  15. ctx.body = res;
  16. ctx.status = 200;
  17. ctx.app.logger.warn(`[error-handler] BusinessError: ${err.errcode}, ${err.errmsg}`);
  18. ctx.app.logger.debug(err);
  19. } else if (err instanceof AssertionError /* && ctx.acceptJSON */) {
  20. // Assert错误
  21. const errcode = ErrorCode.BADPARAM;
  22. let res = { errcode, errmsg: BusinessError.getErrorMsg(errcode) };
  23. if (options.details) {
  24. res = { errcode, errmsg: BusinessError.getErrorMsg(errcode), details: err.message };
  25. }
  26. ctx.body = res;
  27. ctx.status = 200;
  28. ctx.app.logger.warn(`[error-handler] AssertionError: ${err.message}`);
  29. ctx.app.logger.debug(err);
  30. } else {
  31. throw err;
  32. }
  33. }
  34. };
  35. };