加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 01:41:10 所属栏目:大数据 来源:网络整理
导读:我有一个使用Spring Boot开发的休息Web服务.我能够处理由于我的代码而发生的所有异常,但是假设客户端发布的json对象与我想要对其进行反序列化的对象不兼容,我得到 "timestamp": 1498834369591,"status": 400,"error": "Bad Request","exception": "org.sprin

我有一个使用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...
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读