日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Spring Cloud Gateway的全局异常处理

發(fā)布時間:2025/3/21 javascript 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Spring Cloud Gateway的全局异常处理 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Spring Cloud Gateway中的全局異常處理不能直接用@ControllerAdvice來處理,通過跟蹤異常信息的拋出,找到對應(yīng)的源碼,自定義一些處理邏輯來符合業(yè)務(wù)的需求。

網(wǎng)關(guān)都是給接口做代理轉(zhuǎn)發(fā)的,后端對應(yīng)的都是REST API,返回數(shù)據(jù)格式都是JSON。如果不做處理,當(dāng)發(fā)生異常時,Gateway默認(rèn)給出的錯誤信息是頁面,不方便前端進(jìn)行異常處理。

需要對異常信息進(jìn)行處理,返回JSON格式的數(shù)據(jù)給客戶端。下面先看實現(xiàn)的代碼,后面再跟大家講下需要注意的地方。

自定義異常處理邏輯:

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);} ? ?/*** 獲取異常屬性*/@Overrideprotected 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));} ? ?/*** 指定響應(yīng)處理方法為JSON處理的方法* @param errorAttributes*/@Overrideprotected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) { ? ? ? ?return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);} ? ?/*** 根據(jù)code獲取對應(yīng)的HttpStatus* @param errorAttributes*/@Overrideprotected HttpStatus getHttpStatus(Map<String, Object> errorAttributes) { ? ? ? ?int statusCode = (int) errorAttributes.get("code"); ? ? ? ?return HttpStatus.valueOf(statusCode);} ? ?/*** 構(gòu)建異常信息* @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();} ? ?/*** 構(gòu)建返回的JSON數(shù)據(jù)格式* @param status ? ? ? ?狀態(tài)碼* @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;}}

覆蓋默認(rèn)的配置:

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;/*** 覆蓋默認(rèn)的異常處理* * @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); }

這邊優(yōu)先是用HTML來顯示的,想用JSON的改下就可以了,如下:

protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) { ? ? ? return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse); }
  • getHttpStatus需要重寫

原始的方法是通過status來獲取對應(yīng)的HttpStatus的,代碼如下:

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

如果我們定義的格式中沒有status字段的話,這么就會報錯,找不到對應(yīng)的響應(yīng)碼,要么返回數(shù)據(jù)格式中增加status子段,要么重寫,我這邊返回的是code,所以要重寫,代碼如下:

@Override protected HttpStatus getHttpStatus(Map<String, Object> errorAttributes) { ? ?int statusCode = (int) errorAttributes.get("code"); ? ?return HttpStatus.valueOf(statusCode); } 《新程序員》:云原生和全面數(shù)字化實踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀

總結(jié)

以上是生活随笔為你收集整理的Spring Cloud Gateway的全局异常处理的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。