如何在不同的Jackson序列化失败中具有自定义HTTP响应消息?

问题描述 投票:0回答:2

我有Spring Web @ PostMapping端点,该端点获取JSON和Jackson 2.10。应该将其绑定到带有几个Enum的@ RequestBody DTO。如果为枚举字段传递了无效的字符串值,我得到

InvalidFormatException: Cannot deserialize value of type A from String "foo": not one of the values accepted for Enum class: A

这是很好的情况,但是我的400错误请求中没有任何有意义的消息。

如何为每个失败的枚举提供400个自定义响应消息?

示例:

  • 交易字段的有效值为买和卖

  • 组字段的有效值为A,B,C和D

我可以使用一些javax.validation批注,但找不到合适的批注。

java json spring-mvc jackson
2个回答
0
投票

Jackson转换器类处理InvalidFormatException,并引发泛型HttpMessageNotReadableException。因此,要自定义响应错误消息,我们需要处理HttpMessageNotReadableException而不是InvalidFormatException

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler({HttpMessageNotReadableException.class})
@ResponseBody
public String handleHttpMessageNotReadableException(HttpMessageNotReadableException ex) {
    if(ex.getMessage().contains("Cannot deserialize value of type A")){
        return "Binding failed. Allowed values are A, B and C";
    } else if(ex.getMessage().contains("Cannot deserialize value of type B")){
        return "Binding failed. Allowed values are 1, 2 and 3";
    }
    return ex.getMessage();
}

0
投票

您可以使用@ControllerAdvice添加全局异常处理程序,或使用@ExceptionHandler注释添加特殊的控制器方法。

@Controller
public class SimpleController {

    //other controller methods

    @ExceptionHandler(InvalidFormatException.class)
    public ResponseEntity<Object> errorHandler(InvalidFormatException e) {
        return ResponseEntity.badRequest().body(...);
    }
}

https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-error-handling

更新:Spring MVC的ExceptionHandlerMethodResolver(处理@ExceptionHandler)解开了HttpMessageNotReadableException的原因,因此它将处理InvalidFormatExceptionSPR-14291

© www.soinside.com 2019 - 2024. All rights reserved.