Where does the default JSON errors response in spring-boot-starter-web comes from and how to adjust it?

社会主义新天地 提交于 2019-12-18 20:47:43

问题


I am very happy with the spring-boot project so far, but I'd like to develop a deeper understanding, of how everything is glued together. Using spring-boot-starter-web, spring-boot-starter-data-jpa and hateoas I was able to assemble a nice working REST backend. But I am wondering, how it is done, that e.g. a DataIntegrityViolation is converted nicely into a JSON output like this. I actually like the info being provided, but I wonder, how I could reuse the DataObject being converted to JSON. I just do not understand, where it comes from and where it is configure. Hope you folks can help me out or point me to the relevant parts of documentation or even source code.

{
  "readyState": 4,
  "responseText": "{\"timestamp\":1423155860435,\"status\":500,\"error\":\"Internal Server Error\",\"exception\":\"org.springframework.dao.InvalidDataAccessResourceUsageException\",\"message\":\"could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet\",\"path\":\"/api/catalog/colorfamilies\"}",
  "responseJSON": {
    "timestamp": 1423155860435,
    "status": 500,
    "error": "Internal Server Error",
    "exception": "org.springframework.dao.InvalidDataAccessResourceUsageException",
    "message": "could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet",
    "path": "/api/catalog/colorfamilies"
  },
  "status": 500,
  "statusText": "Internal Server Error"
}

Thx for your help, Marius


回答1:


The output is created by Spring Boot's BasicErrorController. It's used as a fallback when your application hasn't handled an exception using Spring MVC (with an ExceptionHandler or ControllerAdvice, for example) or a container error page.

The JSON is created by an implementation of ErrorAttributes. By default, Spring Boot will use DefaultErrorAttributes. You can customise this by creating your own @Bean that implements ErrorAttributes.

See the error handling section of the Spring Boot documentation for more information.



来源:https://stackoverflow.com/questions/28350445/where-does-the-default-json-errors-response-in-spring-boot-starter-web-comes-fro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!