2015-04-15 22 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);