I'd like to catch all exceptions that are thrown during persisting to DB (specifically org.hibernate.exception.ConstraintViolationException). I'm using Spring framework 4.3.8 Spring Data REST 2.6.3 and Spring Data Jpa 1.11 + Hibernate 5.2.8. My idea is to make use of @ControllerAdvice (or @RestController Advice) and @ExceptionHandler(Throwable.class) - but I can't pretty catch the damn exception. Please tell me in which point my idea is erroneus.
Well, I will make the question even easier. Why won't this exception handling work? (The route /users/hello will work flawless though.)
@RepositoryRestController
@RequestMapping("/users")
public class UsersController
{
@RequestMapping(value = "/hello/{variable}", method = RequestMethod.GET)
public @ResponseBody ResponseEntity<?> hello(@PathVariable String variable) throws Exception
{
if (variable.equals("1")) {
throw new Exception("my exception");
}
else {
return ok("hello world");
}
}
@ExceptionHandler
public String logErrors(Exception e) {
return "error: " +e.getMessage();
}
}