Spring Cloud Gateway自定義異常處理Exception Handler的方法小結(jié)
版本: Spring Cloud 2020.0.3
常見的方法有 實(shí)現(xiàn)自己的 DefaultErrorWebExceptionHandler 或 僅實(shí)現(xiàn)ErrorAttributes.
方法1: ErrorWebExceptionHandler (僅供示意)
自定義一個 GlobalErrorAttributes:
@Component public class GlobalErrorAttributes extends DefaultErrorAttributes{ @Override public Map<String, Object> getErrorAttributes(ServerRequest request, ErrorAttributeOptions options) { Throwable error = super.getError(request); Map<String, Object> map = super.getErrorAttributes(request, options); map.put("status", HttpStatus.BAD_REQUEST.value()); map.put("message", error.getMessage()); return map; } }
實(shí)現(xiàn)一個
@Component @Order(-2) public class GlobalErrorWebExceptionHandler extends AbstractErrorWebExceptionHandler { public GlobalErrorWebExceptionHandler(GlobalErrorAttributes gea, ApplicationContext applicationContext, ServerCodecConfigurer serverCodecConfigurer) { super(gea, new WebProperties.Resources(), applicationContext); super.setMessageWriters(serverCodecConfigurer.getWriters()); super.setMessageReaders(serverCodecConfigurer.getReaders()); } //渲染html或json @Override protected RouterFunction<ServerResponse> getRoutingFunction(final ErrorAttributes errorAttributes) { return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse); } private Mono<ServerResponse> renderErrorResponse(final ServerRequest request) { final Map<String, Object> errorPropertiesMap = getErrorAttributes(request, ErrorAttributeOptions.defaults()); return ServerResponse.status(HttpStatus.BAD_REQUEST) .contentType(MediaType.APPLICATION_JSON) .body(BodyInserters.fromValue(errorPropertiesMap)); } }
方法2, 僅實(shí)現(xiàn)一個 ErrorAttributes, 以覆蓋默認(rèn)的 DefaultErrorAttributes
//Spring 默認(rèn)的就很好了. @Component public class GatewayErrorAttributes extends DefaultErrorAttributes { private static final Logger logger = LoggerFactory.getLogger(GatewayErrorAttributes.class); @Override public Map<String, Object> getErrorAttributes(ServerRequest request, ErrorAttributeOptions options) { Throwable error = super.getError(request); Map<String, Object> errorAttributes = new HashMap<>(8); errorAttributes.put("message", error.getMessage()); errorAttributes.put("method", request.methodName()); errorAttributes.put("path", request.path()); MergedAnnotation<ResponseStatus> responseStatusAnnotation = MergedAnnotations .from(error.getClass(), MergedAnnotations.SearchStrategy.TYPE_HIERARCHY).get(ResponseStatus.class); HttpStatus errorStatus = determineHttpStatus(error, responseStatusAnnotation); //必須設(shè)置, 否則會報錯, 因為 DefaultErrorWebExceptionHandler 的 renderErrorResponse 方法會獲取此屬性, 重新實(shí)現(xiàn) DefaultErrorWebExceptionHandler也可. errorAttributes.put("status", errorStatus.value()); errorAttributes.put("code", errorStatus.value()); //html view用 errorAttributes.put("timestamp", new Date()); //html view 用 errorAttributes.put("requestId", request.exchange().getRequest().getId()); errorAttributes.put("error", errorStatus.getReasonPhrase()); errorAttributes.put("exception", error.getClass().getName()); return errorAttributes; } //從DefaultErrorWebExceptionHandler中復(fù)制過來的 private HttpStatus determineHttpStatus(Throwable error, MergedAnnotation<ResponseStatus> responseStatusAnnotation) { if (error instanceof ResponseStatusException) { return ((ResponseStatusException) error).getStatus(); } return responseStatusAnnotation.getValue("code", HttpStatus.class).orElse(HttpStatus.INTERNAL_SERVER_ERROR); } }
這樣就可以了.
注意注意: 必須設(shè)置 errorAttributes.put("status", errorStatus.value()) , 否則會報錯, 因為 DefaultErrorWebExceptionHandler 的 renderErrorResponse 方法會獲取此屬性. 除非你自己像方法一一樣重新實(shí)現(xiàn) DefaultErrorWebExceptionHandler.
然后在網(wǎng)關(guān)中訪問一個不存在的服務(wù), 即可看到效果.
curl 'http://127.0.0.1:8900/fundmain22/abc/gogogo?id=1000' --header 'Accept: application/json'
{"exception":"org.springframework.web.server.ResponseStatusException","path":"/fundmain22/abc/gogogo","code":404,"method":"GET","requestId":"094e53e5-1","message":"404 NOT_FOUND","error":"Not Found","status":404,"timestamp":"2021-08-09T11:07:44.106+0000"}
感謝網(wǎng)絡(luò)上的各種文章...
到此這篇關(guān)于Spring Cloud Gateway自定義異常處理Exception Handler的文章就介紹到這了,更多相關(guān)Spring Cloud Gateway自定義異常處理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 解決使用RestTemplate時報錯RestClientException的問題
- Java ClassCastException異常解決方案
- java.lang.NumberFormatException異常解決方案詳解
- java.lang.NullPointerException異常問題解決方案
- Java中Exception和Error的區(qū)別詳解
- Java異常 Factory method''sqlSessionFactory''rew exception;ested exception is java.lang.NoSuchMethodError:
- 解析PHP中Exception異常機(jī)制
- Java java.lang.InstantiationException異常案例詳解
相關(guān)文章
springboot中用fastjson處理返回值為null的屬性值
在本篇文章里小編給大家整理的是一篇關(guān)于springboot中用fastjson處理返回值問題詳解內(nèi)容,需要的朋友們參考下。2020-03-03一文了解SpringBoot是如何連接數(shù)據(jù)庫的
Spring Boot提供了一系列的開箱即用的功能和特性,使得開發(fā)人員可以快速構(gòu)建和部署應(yīng)用程序,下面這篇文章主要給大家介紹了關(guān)于SpringBoot是如何連接數(shù)據(jù)庫的相關(guān)資料,需要的朋友可以參考下2023-06-06Java并發(fā)工具類LongAdder原理實(shí)例解析
這篇文章主要介紹了Java并發(fā)工具類LongAdder原理實(shí)例解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-05-05Springmvc文件上傳實(shí)現(xiàn)流程解析
這篇文章主要介紹了Springmvc文件上傳實(shí)現(xiàn)流程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-09-09