网关全局异常处理
网关默认错误
json
{
"timestamp": "...",
"path": "/api/auth/oauth/jwt/token",
"status": 500,
"error": "Internal Server Error",
"requestId": "15fede8c-7"
}全局异常处理
实现一个 GlobalErrorAttributes Bean:
@Component
public class GlobalErrorAttributes extends DefaultErrorAttributes {
private static final Logger logger = LoggerFactory.getLogger(GlobalErrorAttributes.class);
@Override
public Map<String, Object> getErrorAttributes(ServerRequest request, ErrorAttributeOptions options) {
Throwable error = super.getError(request);
logger.error("网关处理异常", error);
Map<String, Object> map = new HashMap<>();
map.put("success", false);
map.put("status", HttpStatus.BAD_REQUEST.value());
map.put("msg", error.getMessage());
map.put("data", null);
return map;
}
}实现一个 GlobalErrorWebExceptionHandler Bean
@Component
@Order(-2)
public class GlobalErrorWebExceptionHandler extends AbstractErrorWebExceptionHandler {
public GlobalErrorWebExceptionHandler(GlobalErrorAttributes gea,
ApplicationContext applicationContext,
ServerCodecConfigurer serverCodecConfigurer) {
super(gea, new WebProperties.Resources(), applicationContext);
super.setMessageWriters(serverCodecConfigurer.getWriters());
super.setMessageReaders(serverCodecConfigurer.getReaders());
}
@Override
protected RouterFunction<ServerResponse> getRoutingFunction(final ErrorAttributes errorAttributes) {
return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
}
private Mono<ServerResponse> renderErrorResponse(final ServerRequest request) {
final Map<String, Object> errorPropertiesMap = getErrorAttributes(request, ErrorAttributeOptions.defaults());
return ServerResponse.status(HttpStatus.OK) // 返回成功
.contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(errorPropertiesMap));
}
}
剑鸣秋朔