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
Exception Handler Define a class that extends the RuntimeException class. You can define the @ExceptionHandler method to handle the exceptions as shown. This method should be used for writing the Controller Advice class file. Now, use the code given below to throw the exception from the API.
Altogether, the most common way is to use @ExceptionHandler on methods of @ControllerAdvice classes so that the exception handling will be applied globally or to a subset of controllers. ControllerAdvice is an annotation introduced in Spring 3.2, and as the name suggests, is “Advice” for multiple controllers.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With