Springboot版本:2.7.2
Spring版本:5.3.22
贴代码就完事了
@Component // 注册
@Order(-2) // 排在DefaultExceptionHandler前面,它是-1
public class ExceptionHandler extends AbstractErrorWebExceptionHandler {
private final Logger logger = LoggerFactory.getLogger(ExceptionHandler.class);
public ExceptionHandler(ErrorAttributes errorAttributes, WebProperties webProperties, ApplicationContext applicationContext,
ObjectProvider<ViewResolver> viewResolvers, ServerCodecConfigurer serverCodecConfigurer) {
super(errorAttributes, webProperties.getResources(), applicationContext);
this.setViewResolvers(viewResolvers.orderedStream().collect(Collectors.toList()));
this.setMessageWriters(serverCodecConfigurer.getWriters());
this.setMessageReaders(serverCodecConfigurer.getReaders());
}
@Override
protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
}
private Mono<ServerResponse> renderErrorResponse(ServerRequest request) {
// 这个是返回默认异常
Map<String, Object> errorPropertiesMap = getErrorAttributes(request,
ErrorAttributeOptions.defaults());
// 可以自定义异常返回类
Test t = new Test("自定义异常处理");
return ServerResponse.status(HttpStatus.BAD_REQUEST)
.contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(errorPropertiesMap)); // 这边
}
}