像Spring一样处理异常

时间:2018-09-25 13:26:41

标签: java spring spring-boot

我想处理异常而无需覆盖默认的spring处理程序进行验证。

如果我没有通过@ControllerAdvice实现异常处理程序,我的验证错误将响应如下:

{
    "timestamp": "2018-09-25T13:15:30.037+0000",
    "status": 400,
    "error": "Bad Request",
    "errors": [
        {
            "codes": [
                "Null.notificationEntity.id",
                "Null.id",
                "Null.java.math.BigInteger",
                "Null"
            ],
            "arguments": [
                {
                    "codes": [
                        "notificationEntity.id",
                        "id"
                    ],
                    "arguments": null,
                    "defaultMessage": "id",
                    "code": "id"
                }
            ],
            "defaultMessage": "must be null",
            "objectName": "notificationEntity",
            "field": "id",
            "rejectedValue": 15,
            "bindingFailure": false,
            "code": "Null"
        }
    ],
    "message": "Validation failed for object='notificationEntity'. Error count: 1",
    "path": "/v1/notifications"
}

上面的回答对我来说很清楚,但是如果我创建一个异常处理程序来处理自己的异常,则必须手动处理@Valid引发的验证错误。 我在这里找到了有关此示例:http://www.springboottutorial.com/spring-boot-validation-for-rest-services

但是在这个例子中,我仍然必须手动实现,结果是:

{
    "timestamp": "2018-09-25T13:07:22.779+0000",
    "status": 400,
    "code": "BAD_REQUEST",
    "error": "Bad Request",
    "message": "org.springframework.validation.BeanPropertyBindingResult: 1 errors\nField error in object 'notificationEntity' on field 'id': rejected value [15]; codes [Null.notificationEntity.id,Null.id,Null.java.math.BigInteger,Null]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [notificationEntity.id,id]; arguments []; default message [id]]; default message [must be null]",
    "path": "/v1/notifications"
}

我的问题是,如何在不覆盖spring验证处理程序的情况下实现自己的异常处理程序,或者如何调用spring验证处理程序以对验证异常保持相同的响应?

1 个答案:

答案 0 :(得分:0)

如果要在ControllerAdvice中捕获异常,则可以访问验证异常(我认为这是具有要复制的结构的异常)。

@ExceptionHandler(ValidationException.class)
@ResponseBody
public ResponseEntity<YourCustomResponse> handleValidationexception(ValidationException e) {
    // probably do some logging
    YourCustomResponse response = buildCustomResponse(e); // build the response payload however you see fit
    return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
}

通过这种方式,您可以设置正文,HTTP标头和在发生ValidationException时返回给客户端的HTTP状态。