如何在hapi.js中自定义验证错误响应?

时间:2021-12-01 08:09:10

When using the config.validate option on a route and a request fails due to validation, hapi returns an error like:

当使用配置。在路由上验证选项,请求由于验证而失败,hapi返回如下错误:

{
    "statusCode": 400,
    "error": "Bad Request",
    "message": "child \"weight\" fails because [\"weight\" is required]",
    "validation": {
        "source": "payload",
        "keys": [
            "weight"
        ]
    }
}

Is there a way to send a different formatted validation error?

是否有方法发送不同格式的验证错误?

1 个解决方案

#1


23  

There are two ways to customize the output:

定制输出有两种方式:

  1. Using the failAction attribute in config.validate:

    使用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);
            }
        }
    }
    
  2. Using the onPreResponse extension point:

    使用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();
    });
    

See the API documentation for more details.

有关更多细节,请参阅API文档。

#1


23  

There are two ways to customize the output:

定制输出有两种方式:

  1. Using the failAction attribute in config.validate:

    使用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);
            }
        }
    }
    
  2. Using the onPreResponse extension point:

    使用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();
    });
    

See the API documentation for more details.

有关更多细节,请参阅API文档。