【发布时间】:2020-09-13 03:13:46
【问题描述】:
我正在使用 joi 在 hapi 上实现自定义验证错误消息。
server.route({
path: '/test/inputname',
method: ['PUT','POST'],
handler: async (request, h) => {
try{
const created = await MemberSchema.addUser(
{"input_name": request.payload.input_name}
)
return h.response(created).code(201);
} catch(err){
console.log(err.message);
return h.response(err.message).code(400);
}
},
options: {
validate: {
payload: Joi.object({
input_name: Joi.string()
.min(2)
.max(30)
.required()
.messages({
'string.base' : `"input_name" should be a type of 'text'`,
'string.empty' : `"input_name" cannot be an empty field`,
'string.min' : `"input_name" should have a minimum length of {#limit}`,
'any.required' : `"input_name" is a required field`,
}),
}),
options:{
allowUnknown: true
,abortEarly: false
}
}
}
});
但是当我发布无效数据时,它总是显示如下。
"statusCode": 400,
"error": "Bad Request",
"message": "Invalid request payload input"
如何解决?
附言 我正在使用以下版本。
node v12.16.2
"@hapi/hapi": "^19.1.1",
"@hapi/joi": "^17.1.1",
【问题讨论】:
-
@RvyPandey 正如您所提到的,需要使用 failAction 进行处理。谢谢。