如何自定义 hapi.js 中的验证错误响应?
How can I customize the validation error response in hapi.js?
当使用 config.validate option on a route 并且请求因验证而失败时,hapi returns 会出现如下错误:
{
"statusCode": 400,
"error": "Bad Request",
"message": "child \"weight\" fails because [\"weight\" is required]",
"validation": {
"source": "payload",
"keys": [
"weight"
]
}
}
有没有办法发送不同格式的验证错误?
自定义输出有两种方式:
在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。
当使用 config.validate option on a route 并且请求因验证而失败时,hapi returns 会出现如下错误:
{
"statusCode": 400,
"error": "Bad Request",
"message": "child \"weight\" fails because [\"weight\" is required]",
"validation": {
"source": "payload",
"keys": [
"weight"
]
}
}
有没有办法发送不同格式的验证错误?
自定义输出有两种方式:
在
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。