【问题标题】:How to override error message in @hapi/joi?如何覆盖@hapi/joi 中的错误消息?
【发布时间】:2020-02-10 17:11:03
【问题描述】:

我正在尝试覆盖 Joi 中的自定义错误消息。

假设我有一个如下模式。

const joiSchema = Joi.object({
  name: Joi.string().required(), 
  email: Joi.string().email().required()
})
try{
    const schema = joiSchema.validateAsync(req.body);
}catch(error){
    error.details.map((detail) => {
        // customize error message
    });
}

我需要发送如下错误消息。

{ errors: { name: "Name is Required.", email: "Email is Required." } }

如何在details 数组中的Validation Error 中获取fieldName 之类的name

【问题讨论】:

    标签: node.js typescript express validation joi


    【解决方案1】:

    我找到了如下解决方法。

    const errors = [];
    err.details.forEach((detail) => {
      const currentMessage = detail.message;
      detail.path.forEach((value) => {
        errors.push({ [value]: currentMessage });
      });
    });
    

    【讨论】:

      【解决方案2】:

      你可以得到错误并像它一样处理


      catch(error){
           var data = data.details;
           var message = data[0].message;  // you can get other fields also like this
           var json={"status":"0","message":message,"data":{}}; // you can customize your json response
      }
      

      【讨论】:

        【解决方案3】:

        以下方法也有帮助

            const errorList = [...errors];
            errors.forEach((error, index) => {
                const tmpError = { ...error };
                tmpError.message = "Your custom error message";
                errorList[index] = tmpError;
            });
            return errorList;
        

        【讨论】:

          猜你喜欢
          • 2020-02-12
          • 2020-03-02
          • 2020-09-13
          • 2011-07-15
          • 2011-04-28
          • 2013-06-09
          • 2019-07-18
          • 2011-06-22
          • 2019-03-20
          相关资源
          最近更新 更多