Improve your Spring Boot Error Handling ... |
Written by Nikos Vaggalis |
Tuesday, 25 May 2021 |
with the Error Handling Spring Boot Starter library. We look at a project that improves on the default Spring boot error handling for REST APIs. According the project's definition this project sets out: to make it easy to have proper and consistent error responses or in other words to fix what's wrong with the default Spring Boot error handling. Which is : 1) Exceptions throw an empty body when @WebMvcTest is in place because Spring Boot's error handling is based on Servlet container error mappings that result in an ERROR dispatch to an ErrorController. MockMvc however is container-less testing so with no Servlet container the exception simply bubbles up with nothing to stop it. A workaround is to go with the alternative of @SpringBootTest 2) Then, there is no error message in the response that indicates the exact problem. In many cases, the response status alone is not enough to know exactly what is the problem. 3) And finally, the exact validation problems are not shown. Error Handling Spring Boot Starter gets these issues fixed by adding:
Those aside you can also customize the error code, add extra fields to the error response, and log exceptions through the error.handling.exception-logging property. As of this month, release 1.6.0 adds a few extras:
That is,before 1.6.0 you were getting "code": "com.company.application.user.UserNotFoundException", now you get "code": "USER_NOT_FOUND",
{ "status": 404, "code": "USER_NOT_FOUND", "message": "Could not find user with id 123" }
The javax.validation.ConstraintViolationException is now supported. This exception is used when you validate on a Service method for example, as opposed to validating the RequestBody in the Controller. Validation annotations on a @RequestParam parameter now leads to the addition of parameterErrors in the error response.
In summary, to improve on the Spring boot defaults and enjoy a better and standardized error handling, go the easy way and just include in your project the Error Handling Spring Boot Starter dependency through Maven or Gradle.
More InformationError Handling Spring Boot Starter release 1.6.0 Error Handling Spring Boot Starter Github Error Handling Spring Boot Starter documentation Related ArticlesCompile Spring Applications To Native Images With Spring Native Netflix's GraphQL for Spring Boot The Insider's Guide to the Java Web Developer Nanodegree
To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.
Comments
or email your comment to: comments@i-programmer.info |
Last Updated ( Tuesday, 25 May 2021 ) |