简体   繁体   中英

Logging unhandled exceptions in Spring Mvc Java

I want to capture the exceptions throughout the whole application and save them to my database. I am having difficulty choosing what approach to use. I know I want the exceptions to be handled globally. I am refering to this source : https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc and I have my @controlleradvice but the exceptions do not come throught it at all. Could anyone provide me with a specific example of how to do this?

Thank you.

You could use a ControllerAdvice and ExceptionHandler annotations together to capture specific exceptions and do whatever you want with them. As @M. Deinum said, fo exception logging you can achieve same result by using logback or log4j Database Appender s but still it's a good idea to capture exceptions in Service Layer and translate them to more appropriate say Status Code s, like this:

@ControllerAdvice(annotations = RestController.class)
public class GenericServiceExceptionHandler {
    @ExceptionHandler(Exception.class)
    public ResponseEntity handleUncaughtException(Exception ex) {
        return badRequest(ex.getMessage()).build();
    }
}

This exception handler, catch all Exception exceptions thrown by beans that annotated by RestController and turn them to a 400 Bad Request response.

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