@RestControllerAdvice的基本使用

简介

@RestControllerAdvice 是 Spring Framework 提供的一个注解,用于全局处理控制器(Controller)层的异常、数据绑定和数据预处理。它是 @ControllerAdvice 和 @ResponseBody 的组合,专门用于 RESTful 风格的应用程序。

基本使用

@RestControllerAdvice 通常与 @ExceptionHandler@ModelAttribute 和 @InitBinder 等注解一起使用,用于全局处理异常、绑定数据或预处理请求。

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

@RestControllerAdvice
public class GlobalExceptionHandler {

    // 处理特定异常
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<String> handleIllegalArgumentException(IllegalArgumentException ex) {
        return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST);
    }

    // 处理所有未捕获的异常
    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleAllExceptions(Exception ex) {
        return new ResponseEntity<>("An error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

处理特定控制器的异常

@RestControllerAdvice 默认会处理所有控制器的异常。如果需要限定只处理特定控制器的异常,可以使用 assignableTypes 或 annotations 参数。

@RestControllerAdvice(assignableTypes = {UserController.class, ProductController.class})
public class SpecificControllerAdvice {

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<String> handleResourceNotFoundException(ResourceNotFoundException ex) {
        return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
    }
}

        全局数据绑定 

@RestControllerAdvice 还可以用于全局数据绑定,例如为所有控制器添加公共的模型属性。

import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalModelAttribute {

    @ModelAttribute
    public void addCommonAttributes(Model model) {
        model.addAttribute("globalAttribute", "This is a global attribute");
    }
}

全局数据预处理

@RestControllerAdvice 可以结合 @InitBinder 对请求参数进行全局预处理。 

import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalDataBinder {

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        // 设置允许绑定的字段
        binder.setAllowedFields("name", "email");

        // 注册自定义编辑器
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }
}

结合自定义响应体

可以结合自定义响应体(如 ApiResponse)返回统一的异常响应格式。 

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

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<ApiResponse> handleIllegalArgumentException(IllegalArgumentException ex) {
        ApiResponse response = new ApiResponse(HttpStatus.BAD_REQUEST.value(), ex.getMessage());
        return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ApiResponse> handleAllExceptions(Exception ex) {
        ApiResponse response = new ApiResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), "An error occurred");
        return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

class ApiResponse {
    private int status;
    private String message;

    public ApiResponse(int status, String message) {
        this.status = status;
        this.message = message;
    }

    // Getters and Setters
}

使用场景

  • 全局异常处理:统一处理控制器层抛出的异常,返回友好的错误信息。

  • 全局数据绑定:为所有控制器添加公共的模型属性。

  • 全局数据预处理:对请求参数进行统一的预处理或验证。

  • 统一响应格式:返回统一的错误响应格式,便于前端处理。

注意事项

  • @RestControllerAdvice 只能处理控制器层的异常,无法处理过滤器(Filter)或拦截器(Interceptor)中的异常。

  • 如果有多个 @RestControllerAdvice 类,Spring 会按照优先级处理(可以通过 @Order 注解指定优先级)。

  • 如果需要处理特定包下的控制器,可以使用 basePackages 参数,例如:

    @RestControllerAdvice(basePackages = "com.example.controller")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值