
Filter的位置相對比較尷尬,在MVC層之外,所以無法使用SpringMVC統一異常處理。
雖然SpringCouldGateway支持MVC注解,可以使用SpringMVC統一異常處理處理異常https://www.jianshu.com/p/6f631f3e00b9
但是對於Filter拋出的異常依然束手無策 : - (
解決方案:
SpringCloudGateway異常處理類間關系
在org.springframework.boot.autoconfigure.web.reactive.error
包下有三個類用於處理異常。
(這里強烈建議看一下源碼,了解一下具體的處理思路)

image.png
很明顯,上面兩個是處理異常的一些邏輯,下面的那個類是異常的配置類,所以我們只需要繼承DefaultErrorWebExceptionHandler
然后將我們
處理異常的邏輯替換原有的邏輯。然后通過配置類,將自己寫的類替換原有的類即可。
需要重寫的方法
@Slf4j public class GlobalExceptionHandler extends DefaultErrorWebExceptionHandler { public GlobalExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties, ErrorProperties errorProperties, ApplicationContext applicationContext) { super(errorAttributes, resourceProperties, errorProperties, applicationContext); } @Override protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) { Throwable error = super.getError(request); // todo 添加自己處理異常的邏輯 return null; } // 指定響應處理方法為JSON處理的方法 @Override protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) { return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse); } //設置返回狀態碼,由於我的返回json里面已經包含狀態碼了,不用這里的狀態碼,所以這里直接設置200即可 @Override protected HttpStatus getHttpStatus(Map<String, Object> errorAttributes) { return HttpStatus.valueOf(200); } }
配置類替換成自己的處理異常類
@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) { GlobalExceptionHandler exceptionHandler = new GlobalExceptionHandler( errorAttributes, this.resourceProperties, this.serverProperties.getError(), this.applicationContext); exceptionHandler.setViewResolvers(this.viewResolvers); exceptionHandler.setMessageWriters(this.serverCodecConfigurer.getWriters()); exceptionHandler.setMessageReaders(this.serverCodecConfigurer.getReaders()); return exceptionHandler; } }
這樣我們就將統一異常處理指向了我們自己寫的處理類了,剩下的就是具體的處理邏輯。
因為我們想延用SpringMVC處理異常的注解,所以我們需要解析SpringMVC的注解,然后做一些相應的邏輯處理即可。具體的思路是這樣的。
- 獲取Spring容器中所有的類上標注
@RestControllerAdvice
注解的所有實例 - 獲取實例里面所有標注
@ExceptionHandler
的方法。 - 創建一個map,key是注解中的value(處理異常的類型),value是方法。這樣我們就將我們可以處理的異常和處理異常的方法關聯起來了。
- 解決異常時,先獲取異常的class和他所有的父類class。依次遍歷map,直到找到第一個對應的處理方法,然后通過反射調用該方法。
@Slf4j @Configuration public class ExceptionHandlerCore implements ApplicationRunner { /** * key是處理異常的類型 * value是處理異常的方法 */ private HashMap<Class<? extends Throwable>, Node> exceptionHandlerMap; /** * 解析類上的注解 * 將處理異常的方法注冊到map中 */ private void register(Object exceptionAdvice) { Method[] methods = exceptionAdvice.getClass().getMethods(); Arrays.stream(methods).forEach(method -> { ExceptionHandler exceptionHandler = method.getAnnotation(ExceptionHandler.class); if (Objects.isNull(exceptionHandler)) { return; } Arrays.asList(exceptionHandler.value()).forEach(a -> exceptionHandlerMap.put(a, new Node(method, exceptionAdvice))); }); } /** * 根據異常對象獲取解決異常的方法 * * @param throwable 異常對象 * @return handler method */ private Node getHandlerExceptionMethodNode(Throwable throwable) { ArrayList<Class<?>> superClass = this.getSuperClass(throwable.getClass()); for (Class<?> aClass : superClass) { Node handlerNode = null; if ((handlerNode = exceptionHandlerMap.get(aClass)) != null) { return handlerNode; } } return null; } @Override public void run(ApplicationArguments args) throws Exception { exceptionHandlerMap = new HashMap<>(); log.info("-------------異常處理容器內存分配完畢-------------"); Map<String, Object> beans = SpringContextHolder.getBeansWithAnnotation(RestControllerAdvice.class); log.info("-------------異常處理對象獲取完畢-------------"); beans.keySet() .stream() .map(beans::get) .forEach(this::register); log.info("-------------異常處理方法注冊完畢-------------"); } /** * 對外暴露的處理異常的方法 * * @param throwable 處理的異常 * @return 調用異常后的返回值 */ public Object handlerException(Throwable throwable) { Node exceptionMethodNode = this.getHandlerExceptionMethodNode(throwable); if (Objects.isNull(exceptionMethodNode)) { throw new RuntimeException("沒有處理異常的方法"); } Object returnResult = null; try { returnResult = exceptionMethodNode.method.invoke(exceptionMethodNode.thisObj, throwable); } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } return returnResult; } /** * 用於存放方法和方法所在的實例 */ private static class Node { Node(Method method, Object thisObj) { this.method = method; this.thisObj = thisObj; } Method method; Object thisObj; } /** * 獲取該類的class以及所有父的class * * @param clazz this.class * @return list */ public ArrayList<Class<?>> getSuperClass(Class<?> clazz) { ArrayList<Class<?>> classes = new ArrayList<>(); classes.add(clazz); Class<?> suCl = clazz.getSuperclass(); while (suCl != null) { classes.add(suCl); suCl = suCl.getSuperclass(); } return classes; } }
將該類,注入到剛才的我們自定義的異常處理類然后調用該類的handlerException
方法即可。
@Slf4j public class GlobalExceptionHandler extends DefaultErrorWebExceptionHandler { @Resource private ExceptionHandlerCore handlerCore; // .... /** * 統一處理異常信息 */ @Override @SuppressWarnings(value = "unchecked") protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) { Throwable error = super.getError(request); //調用處理異常的方法,並將對象轉換成map Object o = handlerCore.handlerException(error); String json = JsonHelper.objectToJson(o); return JsonHelper.jsonToObject(json, HashMap.class); } // ...
涉及到的工具類如下:
JsonHelper
public class JsonHelper { /** * Json美化輸出工具 * @param json json string * @return beauty json string */ public static String toPrettyFormat(String json) { JsonParser jsonParser = new JsonParser(); JsonObject jsonObject = jsonParser.parse(json).getAsJsonObject(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); return gson.toJson(jsonObject); } /** * Json轉換成對象 * @param json json string * @param <T> 對象類型 * @return T */ public static <T> T jsonToObject(String json,Class<T> t){ Gson gson = new Gson(); return gson.fromJson(json,t); } /** * 對象轉換成Json字符串 * @param object obj * @return json string */ public static String objectToJson(Object object){ Gson gson = new Gson(); return gson.toJson(object); } }
SpringContextHolder
@Component public class SpringContextHolder implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringContextHolder.applicationContext = applicationContext; } public static ApplicationContext getApplicationContext() { assertApplicationContext(); return applicationContext; } public static <T> T getBean(Class<T> requiredType) { assertApplicationContext(); return applicationContext.getBean(requiredType); } @SuppressWarnings("unchecked") public static <T> T getBean(String beanName) { assertApplicationContext(); return (T) applicationContext.getBean(beanName); } /** * 通過類上的注解獲取類 * * @param annotation anno * @return map */ public static Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotation) { assertApplicationContext(); return applicationContext.getBeansWithAnnotation(annotation); } private static void assertApplicationContext() { if (SpringContextHolder.applicationContext == null) { throw new RuntimeException("application Context屬性為null,請檢查是否注入了SpringContextHolder!"); } } }
測試
編寫異常處理類
@RestControllerAdvice public class GlobalExceptionHandlerAdvice { @ExceptionHandler(Throwable.class) public xxx handler(Throwable e){ return xxx; } }