代码之家  ›  专栏  ›  技术社区  ›  abu abu

如何将MongoDB错误从Express传递到React

  •  0
  • abu abu  · 技术社区  · 6 年前

    我在一个MERN应用程序中工作。在我的一个快递.js我有独特的电子邮件模式如下

    email: {
       type: String,
       trim: true,
       required: true,
       minlength: 3,
       unique: true
    },
    

    当我保存下面这样的记录时,我正在检查电子邮件地址的唯一性

    address.save()
    .then(address => {
       //other code
    })
    .catch(err => {
       console.log(err);
       res.status(500).json({
         message: 'Error Occured',
             error: err
       });
     });
    

    我到达终点站时出错了。

    { MongoError: E11000 duplicate key error collection: addresses.addresses index: email_1 dup key: { : "nowphp@yahoo.com" }
    [0]     at Function.create (/home/foysal/Videos/my-app/node_modules/mongodb-core/lib/error.js:43:12)
    [0]     at toError (/home/foysal/Videos/my-app/node_modules/mongodb/lib/utils.js:149:22)
    [0]     at coll.s.topology.insert (/home/foysal/Videos/my-app/node_modules/mongodb/lib/operations/collection_ops.js:859:39)
    [0]     at /home/foysal/Videos/my-app/node_modules/mongodb-core/lib/connection/pool.js:532:18
    [0]     at process._tickCallback (internal/process/next_tick.js:61:11)
    [0]   driver: true,
    [0]   name: 'MongoError',
    [0]   index: 0,
    [0]   code: 11000,
    [0]   errmsg:
    [0]    'E11000 duplicate key error collection: addresses.addresses index: email_1 dup key: { : "nowphp@yahoo.com" }',
    [0]   [Symbol(mongoErrorContextSymbol)]: {} }
    

    enter image description here

    errmsg: 'E11000 duplicate key error collection: addresses.addresses index: email_1 dup key: { : "nowphp@yahoo.com" }', Email already Exists 把这个传给反应(前端)。

    更新

    我正在使用下面的代码 express.js

    address.save()
        .then( address => {
            // others code
        })
        .catch( err => {
            const errString = err.toString();
            if (errString.includes("E11000")) return res.status(404).json({ err: 'That email is already in use!' });
        });
    

    我的反应如下

    export const addAddress = value => dispatch => {
      return Axios.post('/api/address', value)
        .then( response => {
          // other code
        })
        .catch( error => {
          console.log('actionError', error )
        });
    };
    

    我在控制台中遇到以下错误

    Error: "Request failed with status code 404"

    enter image description here

    1 回复  |  直到 6 年前
        1
  •  1
  •   Matt Carlotta    6 年前

    你有两个选择:在创建之前检查邮件是否已经存在(更好的选择)或者允许Mongo抛出一个 error object 在用户创建过程中,将其转换为 string 然后检查一下 一串 包括 E11000 .

    工作示例 : https://github.com/mattcarlotta/fullstack-mern-kit (点击 here here )


    const createUser = async (req, res, done) => {
      const {
        email,
        firstName,
        lastName,
        userName,
        backgroundInfo,
        address,
      } = req.body;
    
      if (
        !email
        || !firstName
        || !lastName
        || !userName
        || !backgroundInfo
        || isEmpty(address)
      ) return res.status(400).json({ err: “You must include all required fields to create a new user!” }); // checking if the req.body contains all the required user fields
    
      try {
        const emailTaken = await User.findOne({ email });
        if (emailTaken) return res.status(400).json({ err: “That email is already in use!" }); // checking if the user exists before creation
    
        await User.createUser(req.body); // createUser is a custom static method placed on the model
    
        res
          .status(201)
          .json({ message: `Successfully created ${req.body.userName}.` });
      } catch (err) {
        const errString = err.toString();
    
        if (errString.includes("E11000")) return res.status(400).json({ err: “That email is already in use!" }); // handling the error Mongo throws if the user exists during creation
    
        return res.status(400).json({ err: errString }); // handling any other misc errors
      }
    };
    

    axios 轴心 配置: axiosConfig.js . 此配置最重要的部分是更改错误 interceptor here . 这是专门寻找错误的来源 error.response.data.err . 如果你不使用 err 对于API,则需要更新此 line .

    目的 线 错误.响应.数据先生,呃 存在,如果不存在,则返回泛型 Network Error error.message )信息。

    import axios from '../path/to/axiosConfig' ).

    注意 baseURL 到你的API localhost 而且它是 port 轴心 http://localhost:port/ .

    例如,而不是:

    axios.get("http://localhost:5000/api/user")

    axios.get("user")

    如果您有问题,在提问之前,请参阅上面的github repo,因为它展示了如何集成所有内容。如果您计划在生产中使用这个,那么您需要使用 ENVs better-npm-run 但你可以用 cross-env dotenv

        2
  •  2
  •   diegoaguilar    6 年前

    好吧,如果你看看 Error 对象被记录,你可以观察到 code

    您可以计算这样的属性,如果是这样的话,只需传递一个适当的自定义错误消息。

    address.save()
    .then(address => {
       //other code
    })
    .catch(err => {
       const {code} = err
       console.log(err);
       if (code === 11000) {
         err = new Error('Email already Exists');
       }
       res.status(500).json({
         message: 'Error Occured',
         error: err
       });
     });