Spring Cloud Gateway全局异常处理的方法详解

 更新时间:2018年10月11日 11:21:26   作者:猿天地  
这篇文章主要给大家介绍了关于Spring Cloud Gateway全局异常处理的相关资料,需要的朋友可以参考下

前言

Spring Cloud Gateway是Spring官方基于Spring 5.0,Spring Boot 2.0和Project Reactor等技术开发的网关,Spring Cloud Gateway旨在为微服务架构提供一种简单而有效的统一的API路由管理方式。Spring Cloud Gateway作为Spring Cloud生态系中的网关,目标是替代Netflix ZUUL,其不仅提供统一的路由方式,并且基于Filter链的方式提供了网关基本的功能,例如:安全,监控/埋点,和限流等。

Spring Cloud Gateway 的特征:

  • 基于 Spring Framework 5,Project Reactor 和 Spring Boot 2.0动态路由
  • Predicates 和 Filters 作用于特定路由
  • 集成 Hystrix 断路器
  • 集成 Spring Cloud DiscoveryClient
  • 易于编写的 Predicates 和 Filters
  • 限流
  • 路径重写

Spring Cloud Gateway中的全局异常处理不能直接用@ControllerAdvice来处理,通过跟踪异常信息的抛出,找到对应的源码,自定义一些处理逻辑来符合业务的需求。

网关都是给接口做代理转发的,后端对应的都是REST API,返回数据格式都是JSON。如果不做处理,当发生异常时,Gateway默认给出的错误信息是页面,不方便前端进行异常处理。

需要对异常信息进行处理,返回JSON格式的数据给客户端。下面先看实现的代码,后面再跟大家讲下需要注意的地方。
自定义异常处理逻辑:

package com.cxytiandi.gateway.exception;

import java.util.HashMap;
import java.util.Map;

import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;

/**
 * 自定义异常处理
 * 
 * <p>异常时用JSON代替HTML异常信息<p>
 * 
 * @author yinjihuan
 *
 */
public class JsonExceptionHandler extends DefaultErrorWebExceptionHandler {

 public JsonExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties,
 ErrorProperties errorProperties, ApplicationContext applicationContext) {
 super(errorAttributes, resourceProperties, errorProperties, applicationContext);
 }

 /**
 * 获取异常属性
 */
 @Override
 protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
 int code = 500;
 Throwable error = super.getError(request);
 if (error instanceof org.springframework.cloud.gateway.support.NotFoundException) {
 code = 404;
 }
 return response(code, this.buildMessage(request, error));
 }

 /**
 * 指定响应处理方法为JSON处理的方法
 * @param errorAttributes
 */
 @Override
 protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
 return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
 }

 /**
 * 根据code获取对应的HttpStatus
 * @param errorAttributes
 */
 @Override
 protected HttpStatus getHttpStatus(Map<String, Object> errorAttributes) {
 int statusCode = (int) errorAttributes.get("code");
 return HttpStatus.valueOf(statusCode);
 }

 /**
 * 构建异常信息
 * @param request
 * @param ex
 * @return
 */
 private String buildMessage(ServerRequest request, Throwable ex) {
 StringBuilder message = new StringBuilder("Failed to handle request [");
 message.append(request.methodName());
 message.append(" ");
 message.append(request.uri());
 message.append("]");
 if (ex != null) {
 message.append(": ");
 message.append(ex.getMessage());
 }
 return message.toString();
 }

 /**
 * 构建返回的JSON数据格式
 * @param status 状态码
 * @param errorMessage 异常信息
 * @return
 */
 public static Map<String, Object> response(int status, String errorMessage) {
 Map<String, Object> map = new HashMap<>();
 map.put("code", status);
 map.put("message", errorMessage);
 map.put("data", null);
 return map;
 }

}

覆盖默认的配置:

package com.cxytiandi.gateway.exception;

import java.util.Collections;
import java.util.List;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;

/**
 * 覆盖默认的异常处理
 * 
 * @author yinjihuan
 *
 */
@Configuration
@EnableConfigurationProperties({ServerProperties.class, ResourceProperties.class})
public class ErrorHandlerConfiguration {

 private final ServerProperties serverProperties;

 private final ApplicationContext applicationContext;

 private final ResourceProperties resourceProperties;

 private final List<ViewResolver> viewResolvers;

 private final ServerCodecConfigurer serverCodecConfigurer;

 public ErrorHandlerConfiguration(ServerProperties serverProperties,
          ResourceProperties resourceProperties,
          ObjectProvider<List<ViewResolver>> viewResolversProvider,
          ServerCodecConfigurer serverCodecConfigurer,
          ApplicationContext applicationContext) {
  this.serverProperties = serverProperties;
  this.applicationContext = applicationContext;
  this.resourceProperties = resourceProperties;
  this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
  this.serverCodecConfigurer = serverCodecConfigurer;
 }

 @Bean
 @Order(Ordered.HIGHEST_PRECEDENCE)
 public ErrorWebExceptionHandler errorWebExceptionHandler(ErrorAttributes errorAttributes) {
  JsonExceptionHandler exceptionHandler = new JsonExceptionHandler(
    errorAttributes, 
    this.resourceProperties,
    this.serverProperties.getError(), 
    this.applicationContext);
  exceptionHandler.setViewResolvers(this.viewResolvers);
  exceptionHandler.setMessageWriters(this.serverCodecConfigurer.getWriters());
  exceptionHandler.setMessageReaders(this.serverCodecConfigurer.getReaders());
  return exceptionHandler;
 } 
}

注意点

异常时如何返回JSON而不是HTML?

在org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler中的getRoutingFunction()方法就是控制返回格式的,原代码如下:

@Override
protected RouterFunction<ServerResponse> getRoutingFunction(
 ErrorAttributes errorAttributes) {
  return RouterFunctions.route(acceptsTextHtml(), this::renderErrorView)
 .andRoute(RequestPredicates.all(), this::renderErrorResponse);
}

这边优先是用HTML来显示的,想用JSON的改下就可以了,如下:

protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
 return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
}

getHttpStatus需要重写

原始的方法是通过status来获取对应的HttpStatus的,代码如下:

protected HttpStatus getHttpStatus(Map<String, Object> errorAttributes) {
 int statusCode = (int) errorAttributes.get("status");
 return HttpStatus.valueOf(statusCode);
}

如果我们定义的格式中没有status字段的话,这么就会报错,找不到对应的响应码,要么返回数据格式中增加status子段,要么重写,我这边返回的是code,所以要重写,代码如下:

@Override
protected HttpStatus getHttpStatus(Map<String, Object> errorAttributes) {
 int statusCode = (int) errorAttributes.get("code");
 return HttpStatus.valueOf(statusCode);
}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。

相关文章

  • java 数据结构与算法 (快速排序法)

    java 数据结构与算法 (快速排序法)

    这篇文章主要介绍了java 数据结构与算法(快速排序法),,快速排序法是实践中的一种快速的排序算法,在c++或对java基本类型的排序中特别有用,下面我们一起进入文章学习更详细的内容吧,需要的朋友可以参考下
    2022-02-02
  • SpringBoot整合Redis管道的示例代码

    SpringBoot整合Redis管道的示例代码

    本文将结合实例代码,介绍SpringBoot整合Redis管道,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-07-07
  • java利用oss实现下载功能

    java利用oss实现下载功能

    这篇文章主要为大家详细介绍了java利用oss实现下载功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-10-10
  • java实现客户信息管理系统

    java实现客户信息管理系统

    这篇文章主要为大家详细介绍了java实现客户信息管理系统,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-02-02
  • springboot 配置DRUID数据源的方法实例分析

    springboot 配置DRUID数据源的方法实例分析

    这篇文章主要介绍了springboot 配置DRUID数据源的方法,结合实例形式分析了springboot 配置阿里DRUID数据源的具体步骤与相关操作技巧,需要的朋友可以参考下
    2019-12-12
  • Spring中常见的7种BeanDefinition详解

    Spring中常见的7种BeanDefinition详解

    在 Spring 容器中,我们广泛使用的是一个一个的 Bean,BeanDefinition 从名字上就可以看出是关于 Bean 的定义,下面就跟随小编一起深入了解一下常见的7中BeanDefinition吧
    2023-09-09
  • java代码之谜运算符篇

    java代码之谜运算符篇

    从最简单的运算符加号(+)说起,加号(+)是个二元运算符——也就是说,加号只把两个数联接起来,从来不把第三个或者更多的联接起来
    2012-11-11
  • Java+opencv3.2.0之scharr滤波器

    Java+opencv3.2.0之scharr滤波器

    这篇文章主要为大家详细介绍了Java+opencv3.2.0之scharr滤波器的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-02-02
  • Java全面细致讲解final的使用

    Java全面细致讲解final的使用

    关于final关键字,它也是我们一个经常用的关键字,可以修饰在类上、或者修饰在变量、方法上,以此看来定义它的一些不可变性!像我们经常使用的String类中,它便是final来修饰的类,并且它的字符数组也是被final所修饰的。但是一些final的一些细节你真的了解过吗
    2022-05-05
  • springboot项目中jackson-序列化-处理 NULL教程

    springboot项目中jackson-序列化-处理 NULL教程

    这篇文章主要介绍了springboot项目中jackson-序列化-处理 NULL教程,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-10-10

最新评论