webflux全局异常处理

一、实现ErrorWebExceptionHandler接口

import com.alibaba.fastjson.JSONObject;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import reactor.netty.ByteBufMono;

@Component
@Order(-1)
public class FilterExceptionHandler implements ErrorWebExceptionHandler {
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.OK);
        ResultVO resultVO = ResultVO.failMessageInSuccess(ex.getMessage());  // 自定义的返回对象
        DataBuffer dataBuffer = response.bufferFactory()
                .allocateBuffer().write(JSONObject.toJSONString(resultVO).getBytes());
        //基于流形式
        response.getHeaders().setContentType(MediaType.APPLICATION_STREAM_JSON);
        return response.writeAndFlushWith(Mono.just(ByteBufMono.just(dataBuffer)));
    }
}

二、在需要抛出异常的地方返回Mono.error(new Exception("错误消息"))

return Flux.just(1, 2, 3).collectList().flatMap(list -> {
            if (list.size() <= 4) {
                return Mono.error(new Exception("集合太小!"));
            }
            return Mono.just(list);
        }).flatMap(r -> ok().body(fromValue(r)));

三、测试

postman发送请求,得到结果:

{
    "code": "500",
    "data": {},
    "message": "集合太小!",
    "success": false
}

纠正:

return Mono.error之后,如果流后面还有其他操作,会继续执行,而不是中断流的执行。
如果需要中断流的执行,则需要throw异常

@Test
    public void testError() {
        Flux.range(1, 6).map(n -> {
            if (n == 5) {
//                throw new RuntimeException("exception");
                return Mono.error(new Exception("exception"));
            }
            System.out.println(n);
            return Mono.just(n);
        }).collectList().map(list -> {
            System.out.println(list.size());
            return Mono.just("");
        }).subscribe(System.out::println);
    }

Mono.error结果:

1
2
3
4
6
6
MonoJust

可以看到,5现异常没有打印,但6会正常输出
throw结果:

@Test
    public void testError() {
        Flux.range(1, 6).map(n -> {
            if (n == 5) {
                throw new RuntimeException("exception");
                //return Mono.error(new Exception("exception"));
            }
            System.out.println(n);
            return Mono.just(n);
        }).collectList().map(list -> {
            System.out.println(list.size());
            return Mono.just("");
        }).subscribe(System.out::println);
    }

结果:

1
2
3
4
[ERROR] (main) Operator called default onErrorDropped - reactor.core.Exceptions$ErrorCallbackNotImplemented: java.lang.RuntimeException: exception
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
WebFlux全局异常处理可以通过自定义全局异常处理器来实现。在WebFlux中,我们可以使用`@ControllerAdvice`注解来定义一个全局异常处理器类。下面是一个简单的示例: ```java @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public ResponseEntity<ErrorResponse> handleException(Exception ex) { ErrorResponse errorResponse = new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, "An error occurred"); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse); } @ExceptionHandler(WebExchangeBindException.class) public ResponseEntity<ErrorResponse> handleBindException(WebExchangeBindException ex) { ErrorResponse errorResponse = new ErrorResponse(HttpStatus.BAD_REQUEST, "Invalid request"); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse); } // 添加其他异常处理方法... // 自定义错误响应类 private static class ErrorResponse { private final HttpStatus status; private final String message; public ErrorResponse(HttpStatus status, String message) { this.status = status; this.message = message; } // getter 方法... } } ``` 在上述示例中,`@ControllerAdvice`注解用于声明一个全局异常处理器类。`@ExceptionHandler`注解用于指定处理特定异常的方法。在方法中,我们可以根据具体需求创建自定义的错误响应对象,并将其包装在`ResponseEntity`中返回给客户端。 注意,在WebFlux中,全局异常处理器处理的是异步请求,因此需要返回`Mono<ResponseEntity>`或`Flux<ResponseEntity>`类型的结果。 以上是一个简单的WebFlux全局异常处理的示例,你可以根据实际需求进行扩展和修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值