springboot学习(六十八) springboot-webflux全局异常处理


前言

如果springboot中未使用springmvc的依赖,而是使用了webflux的依赖,全局异常处理的方式需要做给改变。
如果是springmvc,可以通过下面方式处理异常

@Configuration
@Slf4j
public class ErrorPageConfig implements ErrorPageRegistrar {
    @Override
    public void registerErrorPages(ErrorPageRegistry registry) {
        log.info("-----------错误页面路径配置------------");
        registry.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/404"),
                new ErrorPage(HttpStatus.FORBIDDEN, "/403"),
                new ErrorPage(HttpStatus.BAD_REQUEST, "/400"),
                new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500"));
        log.info("-----------错误页面路径配置结束------------");
    }
}

可参见之前的文章:https://blog.csdn.net/u011943534/article/details/80806771
但是使用webflux这样配置是不生效的,还会指向默认的错误页面,如404的错误如下:
在这里插入图片描述
需要自定义处理这样的错误

一、自定义错误处理

public class ErrorHandler extends DefaultErrorWebExceptionHandler {
    /**
     * Create a new {@code DefaultErrorWebExceptionHandler} instance.
     *
     * @param errorAttributes    the error attributes
     * @param resources          the resources configuration properties
     * @param errorProperties    the error configuration properties
     * @param applicationContext the current application context
     * @since 2.4.0
     */
    public ErrorHandler(ErrorAttributes errorAttributes, WebProperties.Resources resources, ErrorProperties errorProperties, ApplicationContext applicationContext) {
        super(errorAttributes, resources, errorProperties, applicationContext);
    }

    @Override
    protected Mono<ServerResponse> renderErrorView(ServerRequest request) {
        Map<String, Object> error = getErrorAttributes(request, ErrorAttributeOptions.defaults());
        int errorStatus = getHttpStatus(error);
        if (404 == errorStatus) {
            return ServerResponse.status(HttpStatus.NOT_FOUND)
                    .contentType(MediaType.APPLICATION_JSON)
//                    .bodyValue(new ResponseEntity(404, "未找到资源"));
                    .bodyValue("未找到资源");
        }
        return super.renderErrorView(request);
    }
}

这里如果遇到404错误,直接返回一个未找到资源的提示,HTTP状态码返回404

二、加载自定义错误处理的配置信息

/**
 *
 * @author zhuquanwen
 * @vesion 1.0
 * @date 2022/1/27 9:03
 * @since jdk1.8
 */
@Configuration
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
@ConditionalOnClass(WebFluxConfigurer.class)
@AutoConfigureBefore(WebFluxAutoConfiguration.class)
@EnableConfigurationProperties({ ServerProperties.class, WebProperties.class })
public class ErrorAutoConfiguration {
    private final ServerProperties serverProperties;

    private final ApplicationContext applicationContext;

    private final WebProperties resourceProperties;

    private final List<ViewResolver> viewResolvers;

    private final ServerCodecConfigurer serverCodecConfigurer;

    public ErrorAutoConfiguration(ServerProperties serverProperties, WebProperties resourceProperties,
                                  ObjectProvider<ViewResolver> viewResolversProvider, ServerCodecConfigurer serverCodecConfigurer,
                                  ApplicationContext applicationContext) {
        this.serverProperties = serverProperties;
        this.applicationContext = applicationContext;
        this.resourceProperties = resourceProperties;
        this.viewResolvers = viewResolversProvider.orderedStream().collect(Collectors.toList());
        this.serverCodecConfigurer = serverCodecConfigurer;
    }

    @Bean
    @ConditionalOnMissingBean(value = ErrorWebExceptionHandler.class, search = SearchStrategy.CURRENT)
    @Order(-2)
    public ErrorWebExceptionHandler errorWebExceptionHandler(ErrorAttributes errorAttributes) {
        DefaultErrorWebExceptionHandler exceptionHandler = new ErrorHandler(errorAttributes,
                this.resourceProperties.getResources(), this.serverProperties.getError(), this.applicationContext);
        exceptionHandler.setViewResolvers(this.viewResolvers);
        exceptionHandler.setMessageWriters(this.serverCodecConfigurer.getWriters());
        exceptionHandler.setMessageReaders(this.serverCodecConfigurer.getReaders());
        return exceptionHandler;
    }

    @Bean
    public ErrorAttributes errorAttributes() {
        return new DefaultErrorAttributes();
    }

}

三、效果

在这里插入图片描述
到这里就把404错误的默认页面修改成JSON方式的自定义返回结构体了,根据实际情况定义这个错误结构体就可以了。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值