当前位置: 移动技术网 > IT编程>开发语言>Java > Spring Cloud Gateway中异常处理

Spring Cloud Gateway中异常处理

2019年02月20日  | 移动技术网IT编程  | 我要评论

 最近我们的项目在考虑使用gateway,考虑使用spring cloud gateway,发现网关的异常处理和spring boot 单体应用异常处理还是有很大区别的。让我们来回顾一下异常。

关于异常是拿来干什么的,很多人老程序员认为就是拿来我们debug的时候排错的,当然这一点确实是异常机制非常大的一个好处,但异常机制包含着更多的意义。

  • 关注业务实现。异常机制使得业务代码与异常处理代码可以分开,你可以将一些你调用数据库操作的代码写在一个方法里而只需要在方法上加上throw db相关的异常。至于如何处理它,你可以在调用该方法的时候处理或者甚至选择不处理,而不是直接在该方法内部添加上if判断如果数据库操作错误该如何办,这样业务代码会非常混乱。
  • 统一异常处理。与上一点有所联系。我当前所在项目的实践是,自定义业务类异常,在controller或service中抛出,让后使用spring提供的异常接口统一处理我们自己在内部抛出的异常。这样一个异常处理架构就非常明了。
  • 程序的健壮性。如果没有异常机制,那么来了个对空对象的某方法调用怎么办呢?直接让程序挂掉?这令人无法接受,当然,我们自己平时写的一些小的东西确实是这样,没有处理它,让后程序挂了。但在web框架中,可以利用异常处理机制捕获该异常并将错误信息传递给我们然后继续处理下个请求。所以异常对于健壮性是非常有帮助的。

异常处理(又称为错误处理)功能提供了处理程序运行时出现的任何意外或异常情况的方法。异常处理使用 try、catch 和 finally 关键字来尝试可能未成功的操作,处理失败,以及在事后清理资源。异常根据意义成三种:业务、系统、代码异常,不同的异常采用不同的处理方式。具体的什么样的异常怎么处理就不说了。

红线和绿线代表两条异常路径

1,红线代表:请求到gateway发生异常,可能由于后端app在启动或者是没启动

2,绿线代表:请求到gateway转发到后端app,后端app发生异常,然后gateway转发后端异常到前端

红线肯定是走gateway自定义异常:

两个类的代码如下(参考:http://cxytiandi.com/blog/detail/20548):

 1 @configuration
 2 @enableconfigurationproperties({serverproperties.class, resourceproperties.class})
 3 public class exceptionhandlerconfiguration {
 4 
 5     private final serverproperties serverproperties;
 6 
 7     private final applicationcontext applicationcontext;
 8 
 9     private final resourceproperties resourceproperties;
10 
11     private final list<viewresolver> viewresolvers;
12 
13     private final servercodecconfigurer servercodecconfigurer;
14 
15     public exceptionhandlerconfiguration(serverproperties serverproperties,
16                                          resourceproperties resourceproperties,
17                                          objectprovider<list<viewresolver>> viewresolversprovider,
18                                          servercodecconfigurer servercodecconfigurer,
19                                          applicationcontext applicationcontext) {
20         this.serverproperties = serverproperties;
21         this.applicationcontext = applicationcontext;
22         this.resourceproperties = resourceproperties;
23         this.viewresolvers = viewresolversprovider.getifavailable(collections::emptylist);
24         this.servercodecconfigurer = servercodecconfigurer;
25     }
26 
27     @bean
28     @order(ordered.highest_precedence)
29     public errorwebexceptionhandler errorwebexceptionhandler(errorattributes errorattributes) {
30         jsonexceptionhandler exceptionhandler = new jsonexceptionhandler(
31                 errorattributes,
32                 this.resourceproperties,
33                 this.serverproperties.geterror(),
34                 this.applicationcontext);
35         exceptionhandler.setviewresolvers(this.viewresolvers);
36         exceptionhandler.setmessagewriters(this.servercodecconfigurer.getwriters());
37         exceptionhandler.setmessagereaders(this.servercodecconfigurer.getreaders());
38         return exceptionhandler;
39     }
 1 public class jsonexceptionhandler extends defaulterrorwebexceptionhandler {
 2 
 3     private static logger logger = loggerfactory.getlogger(jsonexceptionhandler.class);
 4 
 5     public jsonexceptionhandler(errorattributes errorattributes, resourceproperties resourceproperties,
 6                                 errorproperties errorproperties, applicationcontext applicationcontext) {
 7         super(errorattributes, resourceproperties, errorproperties, applicationcontext);
 8     }
 9 
10         /**
11          * 获取异常属性
12          */
13         @override
14         protected map<string, object> geterrorattributes(serverrequest request, boolean includestacktrace) {
15             int code = httpstatus.internal_server_error.value();
16             throwable error = super.geterror(request);
17             if (error instanceof org.springframework.cloud.gateway.support.notfoundexception) {
18                 code = httpstatus.not_found.value();
19             }
20             return response(code, this.buildmessage(request, error));
21         }
22 
23         /**
24          * 指定响应处理方法为json处理的方法
25          * @param errorattributes
26          */
27         @override
28         protected routerfunction<serverresponse> getroutingfunction(errorattributes errorattributes) {
29             return routerfunctions.route(requestpredicates.all(), this::rendererrorresponse);
30         }
31 
32 
33         /**
34          * 根据code获取对应的httpstatus
35          * @param errorattributes
36          */
37         @override
38         protected httpstatus gethttpstatus(map<string, object> errorattributes) {
39             int statuscode = (int) errorattributes.get("code");
40             return httpstatus.valueof(statuscode);
41         }
42 
43         /**
44          * 构建异常信息
45          * @param request
46          * @param ex
47          * @return
48          */
49         private string buildmessage(serverrequest request, throwable ex) {
50             stringbuilder message = new stringbuilder("failed to handle request [");
51             message.append(request.methodname());
52             message.append(" ");
53             message.append(request.uri());
54             message.append("]");
55             if (ex != null) {
56                 message.append(": ");
57                 message.append(ex.getmessage());
58             }
59             return message.tostring();
60         }
61 
62         /**
63          * 构建返回的json数据格式
64          * @param status        状态码
65          * @param errormessage  异常信息
66          * @return
67          */
68         public static map<string, object> response(int status, string errormessage) {
69             map<string, object> map = new hashmap<>();
70             map.put("code", status);
71             map.put("message", errormessage);
72             map.put("data", null);
73             logger.error(map.tostring());
74             return map;
75         }
76     }

绿线代表gateway转发异常

转发的异常,肯定是springboot单体中处理的,至于spring单体中的异常是怎么处理的呢?肯定是用@controlleradvice去做。

1     @exceptionhandler(value = exception.class)
2     @responsebody
3     public appresponse exceptionhandler(httpservletrequest request, exception e) {
4         string ip = requestutil.getipaddress(request);
5         logger.info("调用者ip:" + ip);
6         string errormessage = string.format("url:[%s]%n{%s}", request.getrequesturl().tostring(), e.getmessage());
7         logger.error(errormessage, e);
8         return appresponse.error(httpstatus.internal_server_error.value(), e.getmessage());
9     }

到这里基本上可以了,大家不要试着去用gateway去捕获后端异常,回到最初的起点,api 网关(api gateway)主要负责服务请求路由、组合及协议转换,异常同样也是一样,gateway只负责转发单体应用的异常,不要试图gateway捕获后端服务异常,然后再输出给前端。感谢猿天地的一句惊醒梦中人!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网