从猫鼬唯一索引中捕获重复错误并发送res 409

时间:2019-04-06 00:42:15

标签: javascript node.js mongodb mongoose

我有一个猫鼬模式,在其中我定义了唯一的电子邮件。当我插入重复的电子邮件时,出现猫鼬错误,这是我所期望的,但是我想捕获它并在发生这种情况时发送res.status(409),但我做不到。

我尝试使用 mongoose-beautiful-unique-validation 库来更改我收到并捕获的错误,但我仍然迷路。

我的模式:

'use strict';
const beautifyUnique = require('mongoose-beautiful-unique-validation');

const mongoose = require('mongoose');

// create the schema

const { Schema } = mongoose;

const accountSchema = new Schema({
    uuid: {
        type: String,
        unique: true,
      },
      email: {
        type: String,
        unique: 'This email is already taken ({VALUE})',
      },
    password: String,
    createdAt: Date, 
    verification: {
      verificationCode: String,
      verifiedAt: Date,
    },
  });

accountSchema.plugin(beautifyUnique);
const Account = mongoose.model('Account', accountSchema);

module.exports = Account;

我要捕获的错误:


{ ValidationError: Validation failed
    at ValidationError.inspect (/home/danielromero/Desktop/foodtrack git clone/foodtrack-demo/backend_foodtrack/node_modules/mongoose/lib/error/validation.js:59:24)
    at formatValue (internal/util/inspect.js:453:31)
    at inspect (internal/util/inspect.js:193:10)
    at Object.formatWithOptions (util.js:165:18)
    at Console.(anonymous function) (console.js:188:15)
    at Console.log (console.js:199:31)
    at insertAccountIntoDatabase (/home/danielromero/Desktop/foodtrack git clone/foodtrack-demo/backend_foodtrack/webserver/controllers/account/create-account.js:36:13)
    at process._tickCallback (internal/process/next_tick.js:68:7)
  errors:
   { email:
      { ValidatorError: This email is already taken (sapo@yopmail.com)
          at new ValidatorError (/home/danielromero/Desktop/foodtrack git clone/foodtrack-demo/backend_foodtrack/node_modules/mongoose/lib/error/validator.js:29:11)
          at /home/danielromero/Desktop/foodtrack git clone/foodtrack-demo/backend_foodtrack/node_modules/mongoose-beautiful-unique-validation/index.js:150:39
          at Array.forEach (<anonymous>)
          at /home/danielromero/Desktop/foodtrack git clone/foodtrack-demo/backend_foodtrack/node_modules/mongoose-beautiful-unique-validation/index.js:140:36
          at process._tickCallback (internal/process/next_tick.js:68:7)
        message: 'This email is already taken (sapo@yopmail.com)',
        name: 'ValidatorError',
        properties: [Object],
        kind: 'unique',
        path: 'email',
        value: 'sapo@yopmail.com',
        reason: undefined } },
  _message: 'Validation failed',
  name: 'ValidationError' }

我只想知道如何引用ValidationError消息,并在中间件中告诉我的代码,当这种情况发生时,它必须发送409响应。

1 个答案:

答案 0 :(得分:0)

如果您查看堆栈跟踪,可以看到错误at insertAccountIntoDatabase (/home/danielromero/Desktop/foodtrack git clone/foodtrack-demo/backend_foodtrack/webserver/controllers/account/create-account.js:36:13))的出现位置

您将希望通过拥有代码(可能在您的资源中)来捕获该错误,该代码将抛出的错误转换为适当的响应。看起来可能像这样:

try {
  await Account.create(params);
} catch (err) {
  // You only want to catch errors that you know how to handle
  if (err.ValidationError) return res.status(409).send();
  // hopefully this will get caught by something in your middleware and turned into a 500 with helpful metrics & logging
  throw err;
}

从概念上讲,您想在发生错误时捕获错误-共享的代码配置了猫鼬模式的行为,但您想修改其使用位置。