error-mongo.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. 'use strict';
  2. // const { MongoError } = require('mongodb-core');
  3. const { ValidationError } = require('mongoose').Error;
  4. const { BusinessError, ErrorCode } = require('naf-core').Error;
  5. // mongodb错误处理
  6. const handleMongoError = (ctx, err, options) => {
  7. let errcode = ErrorCode.DATABASE_FAULT;
  8. if (err.code === 11000) {
  9. errcode = ErrorCode.DATA_EXISTED;
  10. } /* else if (err instanceof ValidationError && ctx.acceptJSON) {
  11. // 数据库错误
  12. errcode = ErrorCode.BADPARAM;
  13. }*/
  14. let res = { errcode, errmsg: BusinessError.getErrorMsg(errcode) };
  15. if (options.details) {
  16. // expose details
  17. res = { errcode, errmsg: BusinessError.getErrorMsg(errcode), details: err.message };
  18. }
  19. ctx.body = res;
  20. ctx.status = 200;
  21. ctx.app.logger.warn(`[error-mongo] MongoError: ${err.code}, ${err.message}`);
  22. ctx.app.logger.debug(err);
  23. };
  24. module.exports = (options = {}) => {
  25. return async function(ctx, next) {
  26. try {
  27. await next();
  28. } catch (err) {
  29. if (err.name === 'MongoError' && ctx.acceptJSON) {
  30. // 数据库错误
  31. handleMongoError(ctx, err, options);
  32. } else if (err instanceof ValidationError && ctx.acceptJSON) {
  33. // 数据库错误
  34. handleMongoError(ctx, err, options);
  35. } else {
  36. throw err;
  37. }
  38. }
  39. };
  40. };