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); }
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。