如何处理Spring Rest Web服务中的JSON解析错误

前端之家收集整理的这篇文章主要介绍了如何处理Spring Rest Web服务中的JSON解析错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我有一个使用Spring Boot开发的休息Web服务.我能够处理由于我的代码而发生的所有异常,但是假设客户端发布的json对象与我想要对其进行反序列化的对象不兼容,我得到

"timestamp": 1498834369591,"status": 400,"error": "Bad Request","exception": "org.springframework.http.converter.HttpMessageNotReadableException","message": "JSON parse error: Can not deserialize value 

我想知道是否有一种方法,对于此异常,我可以为客户端提供自定义异常消息.我不知道如何处理这个错误.

最佳答案
要为每个Controller自定义此消息,请在控制器中使用@ExceptionHandler和@ResponseStatus的组合:

    @ResponseStatus(value = HttpStatus.BAD_REQUEST,reason = "CUSTOM MESSAGE HERE")
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public void handleException() {
        //Handle Exception Here...
    }

如果你宁愿定义一次并全局处理这些异常,那么使用@ControllerAdvice类:

@ControllerAdvice
public class CustomControllerAdvice {
    @ResponseStatus(value = HttpStatus.BAD_REQUEST,reason = "CUSTOM MESSAGE HERE")
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public void handleException() {
        //Handle Exception Here...
    }
}
原文链接:https://www.f2er.com/spring/431604.html

猜你在找的Spring相关文章