-
Notifications
You must be signed in to change notification settings - Fork 49
Controller exceptions handling
Sometimes exceptions roam around like crazy in your system and might forget to catch them. Not to worry - we will come to the rescue! Our ControllerExceptionHandler catches all exceptions there are and will present them in a nice JSON format (assuming that you use our JsonViewResolver).
You are a good programmer so most likely you are using some JSR validation implementations. That's great and we'll be happy to present those errors in a nice way.
Beware that this module is not included in default configuration.
Let's assume that we have a following controller
@RestController
class TestController {
@RequestMapping(value = "/test", produces = "application/json", method = RequestMethod.POST)
String test(@RequestBody @Valid TestRequest request, BindingResult result) {
checkIfResultHasErrors(result)
return "OK"
}
private void checkIfResultHasErrors(BindingResult result) {
if (result.hasErrors()) {
throw new BadParametersException(result.getAllErrors())
}
}
}
class TestRequest {
@AssertTrue
boolean shouldBeTrue
}
If validation fails we throw BadParametersException that we catch in ControllerExceptionHandler and using JsonViewResolver we can pretty print that JSON for you!
If you want to use this module just add a dependency:
repositories {
jcenter()
}
dependencies {
compile 'com.ofg:micro-infra-spring-base:0.5.5-SNAPSHOT'
}
and enable this this feature
@Configuration
@EnableExceptionHandler
class MyWebAppConfiguration {
}