当将无效的 JSON POST 到 Spring Data REST(版本 2.2.2)资源时,会引发 HttpMessageNotReadableException 并返回以下 json:
{
"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: org.apache.catalina.connector.CoyoteInputStream@646d9de6; 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: org.apache.catalina.connector.CoyoteInputStream@646d9de6; 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: org.apache.catalina.connector.CoyoteInputStream@646d9de6; 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: org.apache.catalina.connector.CoyoteInputStream@646d9de6; 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。
看起来Spring Data REST的 AbstractRepositoryRestController
在第 97 行定义了一个具有优先级的方法:
@ExceptionHandler({ HttpMessageNotReadableException.class })
@ResponseBody
public ResponseEntity<ExceptionMessage> handleNotReadable(HttpMessageNotReadableException e) {
return badRequest(e);
}
我还尝试扩展<code>ResponseEntityExceptionHandler
使用:Spring Data REST 2.2.2 和 Spring Boot 1.2.2
ta。
更新:在github上提供演示maven项目
处理此问题的一种方法是,使用响应实体ExceptionHandler
扩展Custom响应实体ExceptionHandler
,就像您对一个更改所做的那样:
您可以调用<code>ResponseEntityExceptionHandler
例如:
ErrorInfo er = new ErrorInfo(request.getDescription(false), ex.getLocalizedMessage());
return handleExceptionInternal(ex, er, headers, status, request);