繁体   English   中英

如何自定义 javax.validation.Valid 错误响应

[英]How to customise javax.validation.Valid error response

我有这个 controller:

@RequestMapping(
    method = RequestMethod.GET,
    value = Endpoints.TRUE_MATCH,
    produces = {"application/json"})
public ResponseEntity<ResponseWrapper<List<TrueMatch>>> getTrueMatch(
    @Valid Details details) {
    ...
}

详情包含@NotNull private TransmissionType transmissionType; 枚举在哪里。 如果请求的 transmissionType 参数与任何枚举都不匹配,则响应如下所示:

{
    "status": 400,
    "validationErrors": {
        "transmissionType": "Failed to convert property value of type 'java.lang.String' to required type 'my.application.model.TransmissionType' for property 'transmissionType'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@javax.validation.constraints.NotNull ie.aviva.services.motor.cartellservice.model.TransmissionType] for value 'foo'; nested exception is java.lang.IllegalArgumentException: No enum constant ie.aviva.services.motor.cartellservice.model.TransmissionType.automatic'"
    },
    "title": "Bad Request"
}

是否可以覆盖 transmissionType 中的消息,使响应看起来像这样?

{
    "status": 400,
    "validationErrors": {
        "transmissionType": "Some custom message"
    },
    "title": "Bad Request"
}

您可以为MethodArgumentNotValidException实现处理程序:

当验证用 @Valid 注释的参数失败时抛出异常。

@RestControllerAdvice
public class MyErrorHandler {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<MyErrorResponse> handle(MethodArgumentNotValidException ex) {
        // Fetch whatever data you need from the original exception ex
        // e.g. ex.getAllErrors().getXXXX()
        return ResponseEntity
                .status(HttpStatus.BAD_REQUEST)
                .body(MyErrorResponse.builder()
                        //.whicheverFieldsYouNeed(xxxx)
                        .build());
    }


暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM