使用config.validate option on a route时,由于验证请求失败,hapi会返回如下错误:
{
"statusCode": 400,
"error": "Bad Request",
"message": "child \"weight\" fails because [\"weight\" is required]",
"validation": {
"source": "payload",
"keys": [
"weight"
]
}
}
有没有办法发送不同的格式化验证错误?
答案 0 :(得分:23)
有两种方法可以自定义输出:
使用config.validate
中的failAction
属性:
config: {
validate: {
params: {
name: Joi.string().min(3).max(10)
},
failAction: function (request, reply, source, error) {
error.output.payload.message = 'custom';
return reply(error).code(400);
}
}
}
使用onPreResponse
扩展点:
server.ext('onPreResponse', function (request, reply) {
var response = request.response;
if (response.isBoom && response.data.name === 'ValidationError') {
response.output.payload.message = 'custom';
}
return reply.continue();
});
有关详细信息,请参阅API documentation。