Search code examples
spring-mvcconfigurationspring-bootdefault

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


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


Solution

  • 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.