2015-04-15 23 views
3

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

回答

0

一种方式来处理,这将是,到CustomResponseEntityExceptionHandlerResponseEntityExceptionHandler延伸你有一个变化所做的:

,而不是返回ResponseEntity,你可以调用handleExceptionInternal法中规定,由ResponseEntityExceptionHandler。这个方法以及其他几个参数也包含一个body参数。 body参数可以使用您的自定义Error对象进行设置。

例如:

ErrorInfo er = new ErrorInfo(request.getDescription(false), ex.getLocalizedMessage()); 
return handleExceptionInternal(ex, er, headers, status, request);