2017-06-25 58 views
0

我使用的是Spring Boot 1.5.3,Spring Data REST,Spring HATEOAS,Hibernate。 春季數據REST管理在一個漂亮的方式異常,返回一個良好的格式化JSON對象是這樣的:Spring Data REST在哪裏構建異常JSON回覆?

{ 
    "timestamp": "2017-06-24T16:08:54.107+0000", 
    "status": 500, 
    "error": "Internal Server Error", 
    "exception": "org.springframework.dao.InvalidDataAccessApiUsageException", 
    "message": "org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved beforeQuery current operation : com.test.server.model.workflows.WorkSession.checkPoint -> com.test.server.model.checkpoints.CheckPoint; nested exception is java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved beforeQuery current operation : com.test.server.model.workflows.WorkSession.checkPoint -> com.test.server.model.checkpoints.CheckPoint", 
    "path": "/api/v1/workSessions/start" 
} 

我需要本地化異常消息,我想保持彈簧的數據REST的相同JSON格式,並採取看看他們是如何創建異常對象的。 我正在尋找在源代碼中創建異常的代碼,但我無法找到它。也許ExceptionMessage是有用的,但它沒有最終到達用戶的對象的結構。

創建異常的地方在哪裏?

+0

異常消息在保存階段創建異常。似乎有一些關係到一個非真正創建的對象在DB –

+0

@AngeloImmediata我不關心異常本身。我對Spring Data REST如何以這種方式創建JSON對象感興趣。與例外無關,JSON對象始終如此。我想找到創建該對象的代碼。謝謝 – drenda

回答

1

有一個答案,從有用的鏈接

由於對錯誤處理的文檔中描述的那樣,你可以提供 自己的bean實現ErrorAttributes來控制 內容。

這裏是從文檔例如:

@ControllerAdvice(basePackageClasses = FooController.class) 
public class FooControllerAdvice extends ResponseEntityExceptionHandler { 

    @ExceptionHandler(YourException.class) 
    @ResponseBody 
    ResponseEntity<?> handleControllerException(HttpServletRequest request, Throwable ex) { 
     HttpStatus status = getStatus(request); 
     return new ResponseEntity<>(new CustomErrorType(status.value(), ex.getMessage()), status); 
    } 

    private HttpStatus getStatus(HttpServletRequest request) { 
     Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); 
     if (statusCode == null) { 
      return HttpStatus.INTERNAL_SERVER_ERROR; 
     } 
     return HttpStatus.valueOf(statusCode); 
    } 
    } 

剛剛注入區域設置成handleControllerException方法的MessageSource到的意見,並在handleControllerException得到本地化,你從它似乎異常消息需要