将无效JSON发布到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。
似乎第97行的Spring Data REST的AbstractRepositoryRestController
定义了一个优先级高的方法:
@ExceptionHandler({ HttpMessageNotReadableException.class })
@ResponseBody
public ResponseEntity<ExceptionMessage> handleNotReadable(HttpMessageNotReadableException e) {
return badRequest(e);
}
我也试图扩展ResponseEntityExceptionHandler
,但同样地,也不建议。
使用:Spring Data REST 2.2.2和Spring Boot 1.2.2
TA
答案 0 :(得分:0)
处理此问题的一种方法是,使用'border-radius:1px'
扩展CustomResponseEntityExceptionHandler
,就像更改一次一样:
您可以调用ResponseEntityExceptionHandler
提供的ResponseEntity
方法,而不是返回handleExceptionInternal
。此方法以及其他几个参数也采用body参数。可以使用自定义Error对象设置body参数。
例如:
ResponseEntityExceptionHandler