我有一个使用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的组合:
原文链接:/spring/431604.html @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...
}
}