您可以为此要求创建自己的 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