本文主要研究一下spring 5 webflux的異常處理java
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency>
因爲webflux也支持傳統spring mvc的大部分註解,所以原來的ExceptionHandler也是支持的。react
@RestControllerAdvice public class ExceptionHandlers { private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionHandlers.class); @ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public String serverExceptionHandler(Exception ex) { LOGGER.error(ex.getMessage(),ex); return ex.getMessage(); } }
啓動的時候能夠看到日誌
2018-02-12 19:26:03.249 INFO 7053 --- [ main] o.s.w.r.r.m.a.ControllerMethodResolver : Looking for @ControllerAdvice: org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext@65d09a04: startup date [Mon Feb 12 19:25:59 CST 2018]; root of context hierarchy 2018-02-12 19:26:03.281 INFO 7053 --- [ main] o.s.w.r.r.m.a.ControllerMethodResolver : Detected @ExceptionHandler methods in exceptionHandlers
spring-webflux-5.0.2.RELEASE-sources.jar!/org/springframework/web/reactive/result/method/annotation/ControllerMethodResolver.javaweb
/** * Package-private class to assist {@link RequestMappingHandlerAdapter} with * resolving, initializing, and caching annotated methods declared in * {@code @Controller} and {@code @ControllerAdvice} components: * <ul> * <li>{@code @InitBinder} * <li>{@code @ModelAttribute} * <li>{@code @RequestMapping} * <li>{@code @ExceptionHandler} * </ul> * * @author Rossen Stoyanchev * @since 5.0 */ class ControllerMethodResolver { private static Log logger = LogFactory.getLog(ControllerMethodResolver.class); private final List<SyncHandlerMethodArgumentResolver> initBinderResolvers; private final List<HandlerMethodArgumentResolver> modelAttributeResolvers; private final List<HandlerMethodArgumentResolver> requestMappingResolvers; private final List<HandlerMethodArgumentResolver> exceptionHandlerResolvers; private final ReactiveAdapterRegistry reactiveAdapterRegistry; //...... }
能夠看到支持InitBinder,ModelAttribute,RequestMapping,ExceptionHandler這幾個註解。
@GetMapping(value = "/error",produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public Mono<String> exceptionReturn(){ // throw new RuntimeException("hello"); return Mono.error(new RuntimeException("test error")); }
與傳統mvc不一樣的是,除了直接throw異常外,Mono或Flux能夠直接error一個異常,在exceptionHandlers均可以被接收處理
webflux支持mvc的註解,是一個很是便利的功能,相比較於RouteFunction,自動掃描註冊比較省事。異常處理能夠沿用ExceptionHandler。spring