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

w9apscun  于 2023-02-04  发布在  Spring
关注(0)|答案(2)|浏览(128)

我有一个用Sping Boot 开发的REST Web服务,我能够处理所有由于我的代码而发生的异常,但是假设客户端发布的json对象与我想用它去串行化的对象不兼容,我得到

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

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

7kqas0il

7kqas0il1#

要为每个Controller自定义此消息,请在Controller中组合使用@ExceptionHandler@ResponseStatus

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

如果您希望定义一次并全局处理这些Exceptions,则使用@ControllerAdvice类:

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

xam8gpfp2#

您还可以扩展ResponseEntityExceptionHandler并覆盖方法handleHttpMessageNotReadable(Kotlin中的示例,但在Java中非常相似):

override fun handleHttpMessageNotReadable(ex: HttpMessageNotReadableException, headers: HttpHeaders, status: HttpStatus, request: WebRequest): ResponseEntity<Any> {
    val entity = ErrorResponse(status, ex.message ?: ex.localizedMessage, request)
    return this.handleExceptionInternal(ex, entity as Any?, headers, status, request)
}

相关问题