Skip to content
This repository has been archived by the owner on May 11, 2021. It is now read-only.

Controller exceptions handling

mariuszs edited this page Nov 5, 2014 · 3 revisions

Description

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.

Example of usage

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!

Module configuration

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 {
}