Spring Cloud实战小贴士:Zuul统一异常处理,Java面试基础技能罗列
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.stereotype.Component;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
@Component
public class ErrorFilter extends ZuulFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(ErrorFilter.class);
@Override
public String filterType() {
return "error";
}
@Override
public int filterOrder() {
return 10;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() {
RequestContext ctx = RequestContext.getCurrentContext();
Throwable throwable = ctx.getThrowable();
HttpServletResponse response = ctx.getResponse();
try {
if (throwable != null) {
LOGGER.error("Error during filtering", throwable);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
throwable.printStackTrace(new PrintStream(baos));
String exceptionStackTrace = new String(baos.toByteArray());
response.getWriter().write("Unexpected error occurred. Please try again later. StackTrace: " + exceptionStackTrace);
}
} catch (IOException e) {
LOGGER.error("Error while writing the response", e);
}
return null;
}
}
这段代码定义了一个Zuul过滤器,用于处理Zuul中出现的异常。它捕获异常信息,记录错误日志,并向客户端返回一个错误信息。这种异常处理方式有利于保持服务的健壮性,并向用户传递一个更为友好的错误信息。
评论已关闭