【问题标题】:String insted of whitelabel error page in webflux?webflux中的字符串而不是whitelabel错误页面?
【发布时间】:2020-05-25 02:36:00
【问题描述】:

当我使用 org.springframework.boot:spring-boot-starter-web 时,我可以删除 Whitelabel 错误页面,而不是显示我的消息,当链接未找到的资源:

application.yml

server:
  error:
    whitelabel:
      enabled: false
spring:
  mvc:
    throw-exception-if-no-handler-found: true
  resources:
    add-mappings: false

NotFoundResource.class

@RestControllerAdvice
class NotFoundResource {

    @ExceptionHandler(NoHandlerFoundException.class)
    public String handleNotFoundResource() {

        return "Requested resource wasn't found on the server"
    }
}

我该如何使用 webflux?在 weblux 中不包含 NoHandlerFoundException.class。

【问题讨论】:

    标签: spring spring-boot spring-webflux


    【解决方案1】:

    您可以为此要求创建自己的 ErrorWebExceptionHandler 类。 Spring boot documentation 对此提供了见解。

    [引用自文档]

    要改变错误处理行为,你可以实现 ErrorWebExceptionHandler 并注册该类型的 bean 定义。 因为 WebExceptionHandler 是相当低级的,所以 Spring Boot 也 提供了一个方便的 AbstractErrorWebExceptionHandler 让你 以 WebFlux 函数式的方式处理错误,如下所示 例子

    为了更完整的图片,还可以子类化 DefaultErrorWebExceptionHandler 直接覆盖特定的 方法。

    您可以在 DefaultErrorWebExceptionHandler 类上放置一些断点,并检查它如何呈现错误响应。然后根据您的项目要求,您可以根据需要对其进行自定义。

    这是我尝试过的一个非常简单的事情。

    CustomErrorWebExceptionHandler 类:

    public class CustomErrorWebExceptionHandler extends AbstractErrorWebExceptionHandler {
    
      public CustomErrorWebExceptionHandler(
          ErrorAttributes errorAttributes,
          ResourceProperties resourceProperties,
          ApplicationContext applicationContext) {
        super(errorAttributes, resourceProperties, applicationContext);
      }
    
      @Override
      protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
        return route(all(), this::renderErrorResponse);
      }
    
      private Mono<ServerResponse> renderErrorResponse(ServerRequest serverRequest) {
        Throwable throwable = (Throwable) serverRequest
            .attribute("org.springframework.boot.web.reactive.error.DefaultErrorAttributes.ERROR")
            .orElseThrow(
                () -> new IllegalStateException("Missing exception attribute in ServerWebExchange"));
    
        if (throwable.getMessage().equals("404 NOT_FOUND \"No matching handler\"")) {
          return ServerResponse.status(HttpStatus.BAD_REQUEST).contentType(MediaType.APPLICATION_JSON)
              .body(Mono.just("Requested resource wasn't found on the server"), String.class);
        } else {
          return ServerResponse.status(HttpStatus.BAD_REQUEST).contentType(MediaType.APPLICATION_JSON)
              .body(Mono.just("Some Error happened"), String.class);
        }
      }
    
    }
    

    从该类创建一个 bean:

    @Configuration(proxyBeanMethods = false)
    @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
    @ConditionalOnClass(WebFluxConfigurer.class)
    @AutoConfigureBefore(ErrorWebFluxAutoConfiguration.class)
    public class Beans {
    
      @Bean
      @Order(-1)
      public CustomErrorWebExceptionHandler modelMapper(ErrorAttributes errorAttributes,
          ResourceProperties resourceProperties,
          ApplicationContext applicationContext, ServerCodecConfigurer serverCodecConfigurer,
          ObjectProvider<ViewResolver> viewResolvers) {
    
        CustomErrorWebExceptionHandler customErrorWebExceptionHandler = new CustomErrorWebExceptionHandler(
            errorAttributes, resourceProperties,
            applicationContext);
    
        customErrorWebExceptionHandler
            .setViewResolvers(viewResolvers.orderedStream().collect(Collectors.toList()));
        customErrorWebExceptionHandler.setMessageWriters(serverCodecConfigurer.getWriters());
        customErrorWebExceptionHandler.setMessageReaders(serverCodecConfigurer.getReaders());
    
        return customErrorWebExceptionHandler;
      }
    }
    

    application.properties:

    server.error.whitelabel.enabled=false
    spring.mvc.throw-exception-if-no-handler-found=true
    spring.resources.add-mappings=false
    

    这个 StackOverflow 答案很有帮助。 https://stackoverflow.com/a/52508800/11251146

    【讨论】:

      猜你喜欢
      • 2018-07-27
      • 1970-01-01
      • 2023-03-13
      • 2020-08-24
      • 2018-06-09
      • 2017-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多