@ControllerAdvice 使用场景

2024-01-10 13:37:20

@ControllerAdvice is an annotation in Spring Framework that is used to handle exceptions globally across multiple controllers in a Spring MVC application.

By using this annotation, you can define methods that will be applied to all controllers or specific controllers to handle exceptions thrown during request processing. These methods can perform actions such as logging the exception, customizing the error response, or redirecting to an error page.

Here’s a simple example of how to use @ControllerAdvice in a Spring MVC application:

  1. Create a new class and annotate it with @ControllerAdvice . This class will handle exceptions globally across multiple controllers.
@ControllerAdvice
public class GlobalExceptionHandler {
     // Exception handling methods go here
 }
  1. Define methods within the GlobalExceptionHandler class to handle specific exceptions. These methods should be annotated with @ExceptionHandler and specify the exception class they are meant to handle.
@ControllerAdvice
public class GlobalExceptionHandler {
     @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleException(Exception ex) {
        // Handle the exception here
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred");
    }
     @ExceptionHandler(NotFoundException.class)
    public ResponseEntity<String> handleNotFoundException(NotFoundException ex) {
        // Handle the NotFoundException here
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Resource not found");
    }
     // Add more exception handling methods as needed
 }
  1. Customize the exception handling logic within each method. You can log the exception, modify the response, or perform any other necessary actions.
  2. Make sure to import the necessary classes, such as ResponseEntity and HttpStatus .
    That’s it! With this setup, any exceptions thrown within your controllers will be caught by the corresponding @ExceptionHandler methods in the GlobalExceptionHandler class. You can then handle the exceptions and return appropriate responses to the client.

文章来源:https://blog.csdn.net/weixin_37646636/article/details/135500381
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。