@RestControllerAdvice注解是什么?

350 阅读1分钟

@RestControllerAdvice注解是什么?

它是Spring Framework中用于全局处理异常的注解之一。当一个类被标记为@RestControllerAdvice时,它就成为了一个全局的异常处理器,可以用来集中处理应用中抛出的异常。

通过使用@RestControllerAdvice,可以避免在每个Controller中都编写相同的异常处理逻辑,提高了代码的重用性和可维护性。

@RestControllerAdvice通常与@ExceptionHandler一起使用,用来处理特定类型的异常,以及返回自定义的错误响应。例如:

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleGlobalException(Exception ex) {
        return new ResponseEntity<>("An error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}