RxJava错误处理方法及响应式编程失败场景实现咨询
响应式编程中的“失败”是什么?
先给结论:响应式编程里的“失败”和null、空对象/空列表完全是两回事。
它是响应式流的三种核心信号之一(另外两个是onNext数据信号、onComplete完成信号),专门用来表示流的执行出现了错误——比如参数非法、资源不存在、调用第三方服务超时等,一旦触发失败信号,正常的数据流会立即中断,转而进入错误处理流程。
举个实际例子(以Reactor框架为例):
- 空列表是正常的成功结果:
Mono.just(List.of())这个流会正常发送onNext信号(内容是空列表),然后发送onComplete信号,表示流正常结束; - 失败信号是主动抛出异常:
Mono.error(new RuntimeException("查询参数缺失"))这个流不会发送onNext,直接发送onError信号,触发订阅者的错误处理逻辑。
单方法实现你的业务场景
以Spring WebFlux为例,直接在一个控制器方法里就能完成所有逻辑,核心是用响应式操作符做分支判断:
import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Mono; import java.util.List; @RestController public class DemoController { @GetMapping("/items") public Mono<List<String>> getItems(@RequestParam(required = false) String query) { // 1. 未传查询参数:抛出自定义异常,后续映射到对应状态码 if (query == null) { return Mono.error(new MissingQueryParamException("必须传入查询参数")); } // 模拟根据查询参数获取列表的业务逻辑(替换成你的实际调用) Mono<List<String>> itemsMono = fetchItemsByQuery(query); // 2. 返回空列表:抛出404对应的异常 return itemsMono.flatMap(items -> { if (items.isEmpty()) { return Mono.error(new ResourceNotFoundException("未找到匹配的资源")); } return Mono.just(items); }); } // 模拟业务查询方法 private Mono<List<String>> fetchItemsByQuery(String query) { // 示例逻辑:query为"valid"返回非空列表,否则返回空列表 if ("valid".equals(query)) { return Mono.just(List.of("item1", "item2", "item3")); } else { return Mono.just(List.of()); } } // 自定义异常类,区分不同错误场景 static class MissingQueryParamException extends RuntimeException { public MissingQueryParamException(String message) { super(message); } } static class ResourceNotFoundException extends RuntimeException { public ResourceNotFoundException(String message) { super(message); } } }
配合全局异常处理器,把自定义异常映射到对应HTTP状态码:
import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.http.HttpStatus; @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(DemoController.MissingQueryParamException.class) public ResponseEntity<String> handleMissingParam(DemoController.MissingQueryParamException e) { return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST); // 返回400状态码 } @ExceptionHandler(DemoController.ResourceNotFoundException.class) public ResponseEntity<String> handleNotFound(DemoController.ResourceNotFoundException e) { return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND); // 返回404状态码 } }
逻辑说明:
- 先判断查询参数是否存在,不存在直接返回
Mono.error()触发失败信号; - 调用业务方法获取列表后,用
flatMap判断列表是否为空,为空则抛出404异常,否则返回正常列表; - 全局异常处理器负责把不同异常映射到对应状态码,保持控制器方法的逻辑简洁。
内容的提问来源于stack exchange,提问作者mclc
相关产品推荐
相关产品推荐

