前言
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格式的數據給客戶端。下面先看實現的代碼,后面再跟大家講下需要注意的地方。
自定義異常處理邏輯:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
|
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; } } |
覆蓋默認的配置:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
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()方法就是控制返回格式的,原代碼如下:
1
2
3
4
5
6
|
@override protected routerfunction<serverresponse> getroutingfunction( errorattributes errorattributes) { return routerfunctions.route(acceptstexthtml(), this ::rendererrorview) .androute(requestpredicates.all(), this ::rendererrorresponse); } |
這邊優先是用html來顯示的,想用json的改下就可以了,如下:
1
2
3
|
protected routerfunction<serverresponse> getroutingfunction(errorattributes errorattributes) { return routerfunctions.route(requestpredicates.all(), this ::rendererrorresponse); } |
gethttpstatus需要重寫
原始的方法是通過status來獲取對應的httpstatus的,代碼如下:
1
2
3
4
|
protected httpstatus gethttpstatus(map<string, object> errorattributes) { int statuscode = ( int ) errorattributes.get( "status" ); return httpstatus.valueof(statuscode); } |
如果我們定義的格式中沒有status字段的話,這么就會報錯,找不到對應的響應碼,要么返回數據格式中增加status子段,要么重寫,我這邊返回的是code,所以要重寫,代碼如下:
1
2
3
4
5
|
@override protected httpstatus gethttpstatus(map<string, object> errorattributes) { int statuscode = ( int ) errorattributes.get( "code" ); return httpstatus.valueof(statuscode); } |
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。
原文鏈接:https://juejin.im/post/5bbad1405188255c4a7137e1