2017-06-15 38 views
0

我想为zuul服务器创建标准错误页面,以便我可以将异常重定向到此页面?为zuul创建站点错误页面[version 1.1.2]

目前,我创建了一个zuul过滤器捕捉如下zuul例外:

代码片段

@Override 
    public Object run() { 
     try { 
      RequestContext ctx = RequestContext.getCurrentContext(); 
      Object e = ctx.get("error.exception"); 

      if (e != null && e instanceof ZuulException) { 
       ZuulException zuulException = (ZuulException)e; 
       LOG.error("Zuul failure detected: " + zuulException.getMessage(), zuulException); 

       // Remove error code to prevent further error handling in follow up filters 
       ctx.remove("error.status_code"); 

       // Populate context with new response values 
       ctx.setResponseBody("Internal Server Error : Please contact Phoenix Admin"); 
       ctx.getResponse().setContentType("application/json"); 
       ctx.setResponseStatusCode(500); //Can set any error code as excepted 
      } 
     } 
     catch (Exception ex) { 
      LOG.error("Exception filtering in custom error filter", ex); 
      ReflectionUtils.rethrowRuntimeException(ex); 
     } 
     return null; 
    } 

欣赏的任何建议?

+0

将内容类型更改为text/html应该抛出一个页面而不是json。那是你在找什么?或者你想扔一个实际的页面。 –

+0

我期待的内容应该从错误页面读取,而不是硬编码直接进入响应正文,我选择的一个选项是编写一段代码从文件读取内容并填充到responseBody中,但我相信会有点击它@GrinishNepal更好的方法 – Joey

回答

0

我将不得不花费一些时间来了解如何从我正在旅行的错误页面中读取。但通过阅读内容来设置响应主体可能不是一个坏的选择,但肯定可能并不完美。 签出下面的代码,如果有帮助。

此外还添加一些代码,您可能会尝试,并没有工作更容易回答和帮助。 您需要确保过滤器在预过滤器之后运行。

@Override 
     public Object run() { 
      RequestContext ctx = RequestContext.getCurrentContext(); 
      HttpServletRequest request = ctx.getRequest(); 

     String url = UriComponentsBuilder.fromHttpUrl("http://localhost:8082").path("/outage").build() 
            .toUriString(); 
     ctx.set("requestURI", url); 
     return null; 
    } 

检查了这一点的详细资料: - https://github.com/spring-cloud/spring-cloud-netflix/issues/1754

希望这有助于你。