阅读 137

网关 Spring Cloud Zuul 抓取404异常

问题描述

网关zuul配置如下

zuul:
  routes:
    laker:
      path: /laker/**
      url: http://httpbin.org
复制代码

正常访问:http://localhost:8080/laker/get 路由到 http://httpbin.org/get

异常访问:http://localhost:8080/lake123 返回错误页面如下:

想要达到自定义返回json格式的效果。

直接上解决代码

@RestController
@Slf4j
public class DefaultUncaughtErrorControllor implements ErrorController {

    @RequestMapping("/error")
    public Response error(HttpServletRequest request, HttpServletResponse response) {
        HttpStatus statusCode = getHttpStatusCode(request);
        String uri = (String) request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI);
        log.error("error,code:{},uri:{}", statusCode.value(), uri);
        return Response.error(statusCode.value(), "未找到接口", uri);
    }

    private HttpStatus getHttpStatusCode(HttpServletRequest request) {
        try {
            Integer statusCode = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
            if (statusCode == null) {
                return HttpStatus.INTERNAL_SERVER_ERROR;
            }
            return HttpStatus.valueOf(statusCode);
        } catch (Exception e) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
    }


    @Override
    public String getErrorPath() {
        return null;
    }
}
复制代码

具体细节参考我另一篇文章:从零搭建开发脚手架 捕获404异常

效果如下

文章分类
后端
文章标签