![](/img/trans.png)
[英]How to handle error of wrong JSON data in Java Rest Web Service: Jackson JSON Parser Unrecognized token
[英]How to handle JSON Parse Error in Spring Rest Web Service
我有一個使用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...
}
}
您還可以擴展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)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.