1. Zuul异常统一处理
Zuul网关的pre/route/post过滤器在处理过程中的错误统一由error过滤器接收处理,主要有两种实现方式
- 自定义过滤器中通过try catch的方式处理,则通过
org.springframework.cloud.netflix.zuul.filters.post.SendResponseFilter
处理,返回给请求端 - 不做try catch处理,则默认由系统的
org.springframework.cloud.netflix.zuul.filters.post.SendErrorFilter
处理
1.2 PreFilter异常
@Component
@Log4j2
public class MyPreFilterException extends ZuulFilter {
private static final String PRE_TYPE = "pre";
private static final int PRE_ORDER = -1;
private static final boolean PRE_SHOULDFILTER = true;
@Override
public String filterType() {
return PRE_TYPE;
}
@Override
public int filterOrder() {
return PRE_ORDER;
}
@Override
public boolean shouldFilter() {
return PRE_SHOULDFILTER;
}
@Override
public Object run() throws ZuulException {
log.info("This is a pre filter");
RequestContext ctx = RequestContext.getCurrentContext();
try {
myRuntimeException();
}catch ( Exception e) {
ctx.setResponseStatusCode(500);
// ctx.setSendZuulResponse(false);
ctx.setResponseBody("ResponseBody:this is my pre exception");
}
return null;
}
public void myRuntimeException() {
// throw new RuntimeException("runtime exception..."); //PreFilter异常
log.info("PreFilter do something");
}
}
1.2 RouteFilter异常
@Component
@Log4j2
public class MyRouteFilterException extends ZuulFilter {
private static final String ROUTE_TYPE = "route";
private static final int ROUTE_ORDER = -1;
@Override
public String filterType() {
return ROUTE_TYPE;
}
@Override
public int filterOrder() {
return ROUTE_ORDER;
}
@Override
public boolean shouldFilter() {
return true ;
}
@Override
public Object run() throws ZuulException {
RequestContext ctx = RequestContext.getCurrentContext();
try {
myRouteException();
} catch (Exception e) {
ctx.setResponseStatusCode(500);
ctx.setResponseBody("ResponseBody: MyRouteFilterException...");
e.printStackTrace();
}
return null;
}
private void myRouteException() {
// throw new RuntimeException("route filter exception ...");
log.info("RouteFilter do something");
}
}
1.3 PostFilter异常
@Component
@Log4j2
public class MyPostFilterException extends ZuulFilter {
@Override
public String filterType() {
return "post";
}
@Override
public int filterOrder() {
return -1;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() throws ZuulException {
log.info("come in postfilter ....");
RequestContext ctx = RequestContext.getCurrentContext();
try {
myPostFilterException();
} catch (Exception e) {
ctx.setResponseStatusCode(500);
ctx.setResponseBody("ResponseBody:My PostFilter Exception ...");
e.printStackTrace();
}
return null;
}
private void myPostFilterException() {
throw new RuntimeException("My PostFilter Exception");
}
}