投遞無效JSON到春季數據REST(版本2.2.2)資源,一個HttpMessageNotReadableException被拋出下面的JSON返回:定製的ExceptionHandler爲HttpMessageNotReadableException春季數據REST
{
"cause": {
"cause": {
"cause": null,
"message": "Illegal unquoted character ((CTRL-CHAR, code 10)): has to be escaped using backslash to be included in string value\n at [Source: [email protected]; line: 2, column: 20]"
},
"message": "Illegal unquoted character ((CTRL-CHAR, code 10)): has to be escaped using backslash to be included in string value\n at [Source: [email protected]; line: 2, column: 20] (through reference chain: gr.bytecode.exceptionhandling.domain.Book[\"name\"])"
},
"message": "Could not read JSON: Illegal unquoted character ((CTRL-CHAR, code 10)): has to be escaped using backslash to be included in string value\n at [Source: [email protected]; line: 2, column: 20] (through reference chain: gr.bytecode.exceptionhandling.domain.Book[\"name\"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Illegal unquoted character ((CTRL-CHAR, code 10)): has to be escaped using backslash to be included in string value\n at [Source: [email protected]; line: 2, column: 20] (through reference chain: gr.bytecode.exceptionhandling.domain.Book[\"name\"])"
}
有一種明智的方式來覆蓋這種行爲並返回一個自定義的錯誤消息?
這裏是我試過到目前爲止:
我添加了一個自定義@ExceptionHandler
爲例外,但它永遠不會被調用:
@ControllerAdvice
public class CustomResponseEntityExceptionHandler {
@ExceptionHandler(HttpMessageNotReadableException.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
protected ResponseEntity<Object> handleMethodArgumentNotValid(
HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status) {
ErrorMessage errorMessage = new ErrorMessage("some error");
return new ResponseEntity<Object>(errorMessage, headers, status);
}
}
的ErrorMessage是一個簡單的POJO。
看來,春季數據REST的AbstractRepositoryRestController
,在行#97定義的優先級的方法:
@ExceptionHandler({ HttpMessageNotReadableException.class })
@ResponseBody
public ResponseEntity<ExceptionMessage> handleNotReadable(HttpMessageNotReadableException e) {
return badRequest(e);
}
我也試圖擴大ResponseEntityExceptionHandler
但同樣,也沒有勸它。
使用:春季數據REST 2.2.2和Spring 1.2.2引導
TA。
更新:Demo maven project available on github