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的错误如下:
springboot学习(六十八) springboot-webflux全局异常处理_第1张图片
需要自定义处理这样的错误

一、自定义错误处理

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();
    }

}

三、效果

springboot学习(六十八) springboot-webflux全局异常处理_第2张图片
到这里就把404错误的默认页面修改成JSON方式的自定义返回结构体了,根据实际情况定义这个错误结构体就可以了。

你可能感兴趣的:(spring,boot,spring,boot,spring,webflux,webflux自定义错误,ErrorHandler)