投递无效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