赞
踩
通过配置fallbackFactory来捕获异常信息,代码如下
@FeignClient(name = "user", fallbackFactory = UserFallBackFactory.class)
public interface UserFeign {
@PostMapping("/get/list")
Map getList();
}
@Component public class UserFallBackFactory implements FallbackFactory<UserFeign> { @Override public UserFeign create(Throwable throwable) { // 捕获具体异常信息 String message= FeginUtil.getMessage(throwable); return new UserFeign() { @Override public Map getList() { Map<String, Object> map = new HashMap<>(); map.put("status", 500); map.put("message", message); return map; } } } }
public class FeginUtil { public static String getMessage(Throwable e) { if (e instanceof FeignException) { FeignException feignException = (FeignException) e; String url = feignException.request().url(); int status = feignException.status(); String message = feignException.getMessage(); if (status == 404) { return "服务未找到:" + url; } if (message.contains("Read timed out")) { return "服务处理请求超时:" + url; } if (message.contains("connect timed out")) { return "服务连接超时:" + url; } } if (e instanceof RuntimeException) { RuntimeException runtimeException = (RuntimeException) e; String message = runtimeException.getMessage(); if (StringUtils.isNotEmpty(message)) { if (message.contains("Load balancer does not have available server for client")) { String[] split = message.split(":"); if (split.length > 2) { return "没有找到可用的服务:" + split[2]; } } if(message.contains("[") && message.contains("]")){ int startIndex = message.lastIndexOf("[") + 1; int endIndex = message.lastIndexOf("]"); String result = message.substring(startIndex, endIndex); JSONObject jsonObject = JSONObject.parseObject(result); return "服务调用异常:" + jsonObject.getString("exception"); } } } return "系统异常:" + e.getMessage(); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。