一、在zuul的errorfilter中处理(我使用的这种)

package com.mortals.iot.module.common.interceptor;import com.alibaba.fastjson.JSONObject;
import com.mortals.iot.framework.config.InterceptorConfig;
import com.mortals.iot.module.login.service.UserCookieInfo;
import com.mortals.iot.module.login.service.UserCookieService;
import com.mortals.iot.module.system.operLog.service.OperLogService;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;@Component
public class ZuulErrorFilter extends ZuulFilter {private static Logger logger = LoggerFactory.getLogger(ZuulErrorFilter.class);@Autowiredprivate OperLogService operLogService;@Autowiredprivate InterceptorConfig config;@Overridepublic String filterType() {return FilterConstants.ERROR_TYPE;}@Overridepublic int filterOrder() {//需要在默认的 SendErrorFilter 之前return -1;}@Overridepublic boolean shouldFilter() {// 只有在抛出异常时才会进行拦截return RequestContext.getCurrentContext().containsKey("throwable");}@Overridepublic Object run() {try {RequestContext requestContext = RequestContext.getCurrentContext();Object e = requestContext.get("throwable");if (e != null && e instanceof ZuulException) {
//                ZuulException zuulException = (ZuulException) e;// 删除该异常信息,不然在下一个过滤器中还会被执行处理requestContext.remove("throwable");//响应信息HttpServletResponse response = requestContext.getResponse();response.setHeader("Content-type", "application/json;charset=UTF-8");response.setCharacterEncoding("UTF-8");int status = response.getStatus();//数据库-记录操作日志HttpServletRequest request = requestContext.getRequest();UserCookieInfo cookie = UserCookieService.getLoginCookie(request, config.getSecurityKey());logger.error("用户:{},接口:{};异常信息:{}",cookie.getUser().getLoginName(),request.getRequestURI(),((ZuulException) e).getMessage());operLogService.saveOperLog(request, cookie.getUser(), "接口异常", null);// 响应给客户端信息PrintWriter pw = null;pw = response.getWriter();JSONObject ret = new JSONObject();ret.put("code", -1);if (status == 504) {ret.put("msg", "请求超时,请稍后再试。");} else {ret.put("msg", "服务异常或升级中,请联系管理员。");}pw.write(ret.toJSONString());pw.close();}} catch (Exception ex) {logger.error("请求路由异常:", ex);}return null;}
}

二、zuul会抛ZuulException,然后转发路径为/error的Controller;(作为替补)


import com.alibaba.fastjson.JSONObject;
import com.mortals.iot.framework.config.InterceptorConfig;
import com.mortals.iot.module.login.service.UserCookieInfo;
import com.mortals.iot.module.login.service.UserCookieService;
import com.mortals.iot.module.system.operLog.service.OperLogService;
import com.netflix.client.ClientException;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletRequest;/*** @Description Zuul全局错误信息封装(路由失败,子服务异常)* @Author gg* @Date 2020/2/20 15:23* @Version 1.0*/
@RestController
public class ZuulGlobalException implements ErrorController {private static Logger logger = LoggerFactory.getLogger(ZuulGlobalException.class);private static final String ERROR_PATH = "/error";@Autowiredprivate OperLogService operLogService;@Autowiredprivate InterceptorConfig config;@Overridepublic String getErrorPath() {return ERROR_PATH;}@RequestMapping(value = ERROR_PATH)@ExceptionHandler(value = {ZuulException.class, ClientException.class})public String zuulRrror(HttpServletRequest request, final Exception e) {JSONObject result = new JSONObject();Integer code = (Integer) request.getAttribute("javax.servlet.error.status_code");Exception exception = (Exception) request.getAttribute("javax.servlet.error.exception");//        logger.error("异常信息code:"+code);//记录数据库操作日志UserCookieInfo cookie = UserCookieService.getLoginCookie(request, config.getSecurityKey());String errorMsg = "接口访问异常:用户:" + cookie.getUser().getLoginName()+";异常信息msg:"+exception.getMessage();logger.error(errorMsg);operLogService.saveOperLog(request, cookie.getUser(), errorMsg, null);result.put("code", "-1");result.put("msg", "请求失败,服务异常!请联系管理员或稍后再试");return result.toJSONString();}}

三、FallbackProvider统一封装处理(暂未使用)

package com.mortals.iot.module.common.interceptor;import com.alibaba.fastjson.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;/*** @Description 微服务不可以,统一反馈* TODO 说明:为了记录日志,让zuul自己抛异常,转发给/error处理* @Author hgg* @Date 2020/3/9 15:23* @Version 1.0*/
@Component
public class UserFallbackProvider implements FallbackProvider {private static Log logger = LogFactory.getLog(UserFallbackProvider.class);@Overridepublic String getRoute() {// 表明是为哪个微服务提供回退,如果需要所有调用都支持回退,则return "*"或return nullreturn "*";}@Overridepublic ClientHttpResponse fallbackResponse(String route, Throwable cause) {logger.error("路由回退:"+route+";"+cause.getMessage());return new ClientHttpResponse() {@Overridepublic HttpStatus getStatusCode() throws IOException {// fallback时的状态码return HttpStatus.OK;}@Overridepublic int getRawStatusCode() throws IOException {// 数字类型的状态码,本例返回的其实就是200,详见HttpStatusreturn this.getStatusCode().value();}@Overridepublic String getStatusText() throws IOException {// 状态文本,本例返回的其实就是OK,详见HttpStatusJSONObject ret = new JSONObject();ret.put("code", -1);//请求失败,服务异常!请联系管理员或稍后再试ret.put("msg", "服务异常或升级中,请稍后再试。");return ret.toJSONString();}@Overridepublic void close() {}/*** 封装统一响应* @return* @throws IOException*/@Overridepublic InputStream getBody() throws IOException {logger.info(route+"服务异常,调用失败");return new ByteArrayInputStream(getStatusText().getBytes());// 响应体
//        return new ByteArrayInputStream("用户微服务不可用,请稍后再试。".getBytes());}@Overridepublic HttpHeaders getHeaders() {// headers设定HttpHeaders headers = new HttpHeaders();MediaType mt = new MediaType("application","json", Charset.forName("UTF-8"));headers.setContentType(mt);return headers;}};}
}

推荐文章一:zuul统一异常处理

Spring Cloud Zuul统一异常处理相关推荐

  1. Spring Cloud 如何统一异常处理?写得太好了!

    欢迎关注方志朋的博客,回复"666"获面试宝典 作者:BNDong 链接:www.cnblogs.com/bndong/p/10135370.html 前言 在启动应用时会发现在控 ...

  2. ​Spring Cloud中统一异常处理是怎么做的?

    作者:BNDong www.cnblogs.com/bndong/p/10135370.html 在启动应用时会发现在控制台打印的日志中出现了两个路径为 {[/error]} 的访问地址,当系统中发送 ...

  3. ​Spring Cloud:统一异常处理

    作者:BNDong www.cnblogs.com/bndong/p/10135370.html 在启动应用时会发现在控制台打印的日志中出现了两个路径为 {[/error]} 的访问地址,当系统中发送 ...

  4. Spring Cloud:统一异常处理

    在启动应用时会发现在控制台打印的日志中出现了两个路径为 {[/error]} 的访问地址,当系统中发送异常错误时,Spring Boot 会根据请求方式分别跳转到以 JSON 格式或以界面显示的 /e ...

  5. Spring Cloud实战小贴士:Zuul统一异常处理(一)

    在上一篇<Spring Cloud源码分析(四)Zuul:核心过滤器>一文中,我们详细介绍了Spring Cloud Zuul中自己实现的一些核心过滤器,以及这些过滤器在请求生命周期中的不 ...

  6. Spring Cloud实战小贴士:Zuul统一异常处理(二)

    在前几天发布的<Spring Cloud实战小贴士:Zuul统一异常处理(一)>一文中,我们详细说明了当Zuul的过滤器中抛出异常时会发生客户端没有返回任何内容的问题以及针对这个问题的两种 ...

  7. Spring Cloud实战小贴士:Zuul统一异常处理(三)【Dalston版】

    本篇作为<Spring Cloud微服务实战>一书关于Spring Cloud Zuul网关在Dalston版本对异常处理的补充.没有看过本书的读书也不要紧,可以先阅读我之前的两篇博文:& ...

  8. Spring Cloud实战Zuul统一异常处理

    Spring Cloud实战Zuul统一异常处理 Spring Cloud Zuul中自己实现的一些核心过滤器,以及这些过滤器在请求生命周期中的不同作用.我们会发现在这些核心过滤器中并没有实现erro ...

  9. spring cloud zuul 原理简介和使用

    一 spring cloud zuul 简介 Spring Cloud Zuul 是 Spring Cloud Netflix 子项目的核心组件之一,可以作为微服务架构中的 API 网关使用,支持动态 ...

最新文章

  1. android 内部存储 清空,Android清空应用内部文件缓存
  2. hbuilder入门之基本配置(php)
  3. IT新人如何快速成长
  4. nodogsplash的内部机制分析
  5. python3.10_概述 — Python 3.10.0a2 文档
  6. Java 中类的静态成员与类的实例对象回收
  7. java字符编码方式总结
  8. 【转】10个推荐的 PACS/DICOM Server开源项目
  9. js关闭setInterval及终止ajax请求
  10. 中国象棋口诀及要领精髓
  11. 16. Zend_Controller
  12. Snmp4j编程简介之三:Snmp
  13. 命令提示符之常用命令
  14. 利用保利威视实现教育视频预览和购买
  15. /etc/issue和/etc/motd
  16. MVC项目文件夹说明和创建MVC
  17. 矩阵“特征值”要表示什么“特征”
  18. 新型网络诈骗缘何层出不穷?
  19. Qt 字体字号和字体像素关系
  20. Linux抓包和分析

热门文章

  1. 《嵌入式 – GD32开发实战指南》第20章 GD32的存储结构
  2. Android视频播放器实现小窗口和全屏状态切换
  3. 对txt文件中的文件内容进行断句
  4. 20200220–靶场记录,web渗透+内网渗透完整版
  5. Swagger结合PostMan完成接口自动化测试
  6. 100G波分复用(WDM)宽带传输设备
  7. 免费、付费换IP大集合,你要的这都有【芝麻http】
  8. 凸优化学习笔记(一)
  9. 当我入门虚拟现实的时候,我学了什么?
  10. API管理源码一个你从未见过的全新版本界面