SpringCloud gateway全域性異常處理,以及後臺的服務異常response的異常包裝
阿新 • • 發佈:2018-12-29
有兩個類
/** * @author wuweifeng wrote on 2018/11/2. */ @Configuration public class ExceptionConfig { /** * 自定義異常處理[@@]註冊Bean時依賴的Bean,會從容器中直接獲取,所以直接注入即可 */ @Primary @Bean @Order(Ordered.HIGHEST_PRECEDENCE) public ErrorWebExceptionHandler errorWebExceptionHandler(ObjectProvider<List<ViewResolver>> viewResolversProvider, ServerCodecConfigurer serverCodecConfigurer) { JsonExceptionHandler jsonExceptionHandler = new JsonExceptionHandler(); jsonExceptionHandler.setViewResolvers(viewResolversProvider.getIfAvailable(Collections::emptyList)); jsonExceptionHandler.setMessageWriters(serverCodecConfigurer.getWriters()); jsonExceptionHandler.setMessageReaders(serverCodecConfigurer.getReaders()); return jsonExceptionHandler; } }
package com.maimeng.apigateway.config.exception; /** * @author wuweifeng wrote on 2018/11/2. */ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler; import org.springframework.cloud.gateway.support.NotFoundException; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.codec.HttpMessageReader; import org.springframework.http.codec.HttpMessageWriter; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.util.Assert; import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.server.RequestPredicates; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerRequest; import org.springframework.web.reactive.function.server.ServerResponse; import org.springframework.web.reactive.result.view.ViewResolver; import org.springframework.web.server.ResponseStatusException; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @classDesc: 統一異常處理, 參考{@link org.springframework.web.server.AbstractErrorWebExceptionHandler}修改 * @author: chenggang */ public class JsonExceptionHandler implements ErrorWebExceptionHandler { private static final Logger log = LoggerFactory.getLogger(JsonExceptionHandler.class); /** * MessageReader */ private List<HttpMessageReader<?>> messageReaders = Collections.emptyList(); /** * MessageWriter */ private List<HttpMessageWriter<?>> messageWriters = Collections.emptyList(); /** * ViewResolvers */ private List<ViewResolver> viewResolvers = Collections.emptyList(); /** * 儲存處理異常後的資訊 */ private ThreadLocal<Map<String, Object>> exceptionHandlerResult = new ThreadLocal<>(); /** * 參考AbstractErrorWebExceptionHandler */ public void setMessageReaders(List<HttpMessageReader<?>> messageReaders) { Assert.notNull(messageReaders, "'messageReaders' must not be null"); this.messageReaders = messageReaders; } /** * 參考AbstractErrorWebExceptionHandler */ public void setViewResolvers(List<ViewResolver> viewResolvers) { this.viewResolvers = viewResolvers; } /** * 參考AbstractErrorWebExceptionHandler */ public void setMessageWriters(List<HttpMessageWriter<?>> messageWriters) { Assert.notNull(messageWriters, "'messageWriters' must not be null"); this.messageWriters = messageWriters; } @Override public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) { // 按照異常型別進行處理 HttpStatus httpStatus; String body; if (ex instanceof NotFoundException) { httpStatus = HttpStatus.NOT_FOUND; body = "Service Not Found"; } else if (ex instanceof ResponseStatusException) { ResponseStatusException responseStatusException = (ResponseStatusException) ex; httpStatus = responseStatusException.getStatus(); body = responseStatusException.getMessage(); } else { httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; body = "Internal Server Error"; } //封裝響應體,此body可修改為自己的jsonBody Map<String, Object> result = new HashMap<>(2, 1); result.put("httpStatus", httpStatus); String msg = "{\"code\":" + httpStatus + ",\"message\": \"" + body + "\"}"; result.put("body", msg); //錯誤記錄 ServerHttpRequest request = exchange.getRequest(); log.error("[全域性異常處理]異常請求路徑:{},記錄異常資訊:{}", request.getPath(), ex.getMessage()); //參考AbstractErrorWebExceptionHandler if (exchange.getResponse().isCommitted()) { return Mono.error(ex); } exceptionHandlerResult.set(result); ServerRequest newRequest = ServerRequest.create(exchange, this.messageReaders); return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse).route(newRequest) .switchIfEmpty(Mono.error(ex)) .flatMap((handler) -> handler.handle(newRequest)) .flatMap((response) -> write(exchange, response)); } /** * 參考DefaultErrorWebExceptionHandler */ protected Mono<ServerResponse> renderErrorResponse(ServerRequest request) { Map<String, Object> result = exceptionHandlerResult.get(); return ServerResponse.status((HttpStatus) result.get("httpStatus")) .contentType(MediaType.APPLICATION_JSON_UTF8) .body(BodyInserters.fromObject(result.get("body"))); } /** * 參考AbstractErrorWebExceptionHandler */ private Mono<? extends Void> write(ServerWebExchange exchange, ServerResponse response) { exchange.getResponse().getHeaders() .setContentType(response.headers().getContentType()); return response.writeTo(exchange, new ResponseContext()); } /** * 參考AbstractErrorWebExceptionHandler */ private class ResponseContext implements ServerResponse.Context { @Override public List<HttpMessageWriter<?>> messageWriters() { return JsonExceptionHandler.this.messageWriters; } @Override public List<ViewResolver> viewResolvers() { return JsonExceptionHandler.this.viewResolvers; } } }
那麼gateway代理的後臺服務,如果出現了異常沒有處理,閘道器也是會直接原文返回給客戶端的。
譬如在gateway後面有一個服務出了異常,當客戶端請求時:
如果我們通用的返回值,並不是這麼定義的,譬如我都是用code=200,message=xxx之類的json。那麼當這樣的返回值給客戶端時,就會有問題了,因為不統一。而且我們無法保證閘道器後面的微服務都能捕獲異常並返回統一的格式,所以,就需要在閘道器處做一層封裝。對返回值、尤其是非正常的返回值做一個包裝。
通過這篇文章獲取到返回值後,可以通過判斷json字串是否包含code:xxx的字樣,來判斷後臺的服務是否異常了。然後通過修改返回值,加上我們通用的返回值欄位即可。