You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot Reactive全局异常处理器配置:按异常类型设响应状态码

在Reactive Spring Boot中全局配置异常响应状态并保留默认JSON格式

要在WebFlux版本的Spring Boot中实现全局异常处理,同时保留框架默认的JSON错误格式,你可以通过以下两种方式实现:

方式一:全局异常处理器(推荐)

使用@RestControllerAdvice结合@ExceptionHandler,配合Spring Boot自动配置的ErrorAttributes生成和默认格式一致的错误响应,同时指定对应异常的状态码。

代码实现

import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.Map;

@RestControllerAdvice
public class GlobalReactiveExceptionHandler {

    private final ErrorAttributes errorAttributes;

    // 注入Spring Boot默认的ErrorAttributes实例
    public GlobalReactiveExceptionHandler(ErrorAttributes errorAttributes) {
        this.errorAttributes = errorAttributes;
    }

    // 处理IllegalArgumentException,返回400 Bad Request
    @ExceptionHandler(IllegalArgumentException.class)
    public Mono<ResponseEntity<Map<String, Object>>> handleIllegalArgument(ServerWebExchange exchange, IllegalArgumentException ex) {
        // 生成和默认错误响应结构一致的属性集合
        Map<String, Object> errorDetails = errorAttributes.getErrorAttributes(
                exchange, org.springframework.boot.web.error.ErrorAttributeOptions.defaults());
        
        // 返回400状态码及默认格式的错误JSON
        return Mono.just(ResponseEntity.badRequest().body(errorDetails));
    }

    // 可扩展:处理自定义业务异常
    @ExceptionHandler(BusinessException.class)
    public Mono<ResponseEntity<Map<String, Object>>> handleBusinessException(ServerWebExchange exchange, BusinessException ex) {
        Map<String, Object> errorDetails = errorAttributes.getErrorAttributes(exchange, org.springframework.boot.web.error.ErrorAttributeOptions.defaults());
        return Mono.just(ResponseEntity.status(HttpStatus.FORBIDDEN).body(errorDetails));
    }
}

说明

  • @RestControllerAdvice在WebFlux环境下生效,负责全局捕获控制器抛出的异常
  • ErrorAttributes是Spring Boot生成默认错误响应的核心组件,返回的Map包含timestamp、status、error、message、path等标准字段,和框架默认格式完全一致
  • 通过ServerWebExchange获取当前请求上下文,确保错误信息包含请求路径等上下文数据

方式二:直接抛出ResponseStatusException

如果是局部场景处理异常,可直接在业务代码中抛出ResponseStatusException,Spring Boot会自动生成默认格式的错误响应:

import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;

// 在业务逻辑中抛出
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "参数格式非法", new IllegalArgumentException("无效的ID"));

这种方式无需编写全局处理器,适合零散的异常处理场景,但无法统一管控所有同类型异常。

可选:自定义错误格式

如果需要在默认格式基础上添加自定义字段,可以继承DefaultErrorAttributes并扩展属性:

import org.springframework.boot.web.reactive.error.DefaultErrorAttributes;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import java.util.Map;

@Component
public class CustomErrorAttributes extends DefaultErrorAttributes {
    @Override
    public Map<String, Object> getErrorAttributes(ServerWebExchange exchange, ErrorAttributeOptions options) {
        Map<String, Object> attributes = super.getErrorAttributes(exchange, options);
        // 添加自定义字段
        attributes.put("service", "user-center");
        attributes.put("traceId", exchange.getRequest().getHeaders().getFirst("X-Trace-Id"));
        return attributes;
    }
}

之后全局处理器会自动使用这个自定义的ErrorAttributes生成带额外字段的错误响应。


内容的提问来源于stack exchange,提问作者vivi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 02:57:30