简体   繁体   中英

Spring Data REST @ExceptionHandler

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();
    }
}

I've solved the problem. My application main configuration was:

@Configuration
// other neccessary annotations
public class RestApplicationConfig extends RepositoryRestMvcConfiguration {
}

The project was purely Spring Data Rest . To make use of @ExceptionHandler feature you need to run Spring Web MVC . You can do this in either of the ways:

1) Import RepositoryRestMvcConfiguration into your main Spring Web MVC configuration:

@Configuration
@EnableWebMvc
// other neccessary annotations
@Import(RepositoryRestMvcConfiguration.class)
public class WebMvcConfig extends WebMvcConfigurerAdapter{}

2) Use @EnableWebMvc annotation when as main configuration file you have a class that extends the RepositoryRestMvcConfiguration class:

@Configuration
@EnableWebMvc
// other neccessary annotations
public class RestApplicationConfig extends RepositoryRestMvcConfiguration {}

It's worth adding here that in Spring Data REST there is a standard RepositoryRestExceptionHandler class that handles by default all major exception types and loggs them. Thus you don't essentially need to create your own handlers unless you need something more personalized.

What about:

@ExceptionHandler(org.hibernate.exception.ConstraintViolationException.class)
public String logErrors(Exception e) {
    return "error: " +e.getMessage();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM