# 自定义异常处理器
import org.springframework.boot.autoconfigure.web.WebProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.AbstractErrorWebExceptionHandler;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.*;
import reactor.core.publisher.Mono;
import java.util.Map;
@Component
@Order(-1)
public class CustomException extends AbstractErrorWebExceptionHandler {
public CustomException(ErrorAttributes errorAttributes,
ApplicationContext applicationContext,
ServerCodecConfigurer serverCodecConfigurer) {
super(errorAttributes, new WebProperties().getResources(), applicationContext);
super.setMessageWriters(serverCodecConfigurer.getWriters());
super.setMessageReaders(serverCodecConfigurer.getReaders());
}
@Override
protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
return RouterFunctions.route(RequestPredicates.all(), this::readerErrorResponse);
}
private Mono<ServerResponse> readerErrorResponse(ServerRequest serverRequest) {
//获取异常信息
Map<String, Object> map = getErrorAttributes(serverRequest, ErrorAttributeOptions.defaults());
return ServerResponse.status(HttpStatus.NOT_FOUND) //404
.contentType(MediaType.APPLICATION_JSON) //JSON
.body(BodyInserters.fromValue(map)); //响应体
}
}
# 自定义错误内容
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.reactive.error.DefaultErrorAttributes;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import java.util.Map;
@Component
public class CustomException2 extends DefaultErrorAttributes {
@Override
public Map<String, Object> getErrorAttributes(ServerRequest request, ErrorAttributeOptions options) {
// super.getErrorAttributes(request, options); 这里可以不用get ,直接new 一个 hashMap 也可以
Map<String, Object> resError = super.getErrorAttributes(request, options);
resError.put("message", "请求条件不满足");
return resError;
}
}