1. Overview
1.概述
Zuul is a JVM-based router and server-side load balancer by Netflix. Zuul’s rule engine provides flexibility to write rules and filters to enhance routing in a Spring Cloud microservices architecture.
Zuul是Netflix推出的基于JVM的路由器和服务器端负载平衡器。Zuul的规则引擎提供了编写规则和过滤器的灵活性,以增强Spring Cloud微服务架构中的路由。
In this article, we’ll explore how to customize exceptions and error responses in Zuul by writing custom error filters that are run when an error occurs during the code execution.
在这篇文章中,我们将探讨如何在Zuul中通过编写自定义错误过滤器,在代码执行过程中发生错误时运行来定制异常和错误响应。
2. Zuul Exceptions
2.Zuul 例外
All handled exceptions in Zuul are ZuulExceptions. Now, let’s make it clear that ZuulException can’t be caught by @ControllerAdvice and annotating the method by @ExceptionHandling. This is because ZuulException is thrown from the error filter. So, it skips the subsequent filter chains and never reaches the error controller. The following picture depicts the hierarchy of error handling in Zuul:
在Zuul中所有处理的异常都是ZuulExceptions。现在,让我们明确一下,ZuulException不能被@ControllerAdvice捕获,并通过@ExceptionHandling注释该方法。这是因为ZuulException是由错误过滤器抛出的。所以,它跳过了后续的过滤器链,从未到达错误控制器。下图描述了Zuul中错误处理的层次结构。
Zuul displays the following error response when there is a ZuulException:
当出现ZuulException时,Zuul显示以下错误响应。
{
"timestamp": "2022-01-23T22:43:43.126+00:00",
"status": 500,
"error": "Internal Server Error"
}
In some scenarios, we might need to customize the error message or status code in the response of the ZuulException. Zuul filter comes to the rescue. In the next section, we’ll discuss how to extend Zuul’s error filter and customize ZuulException.
在某些情况下,我们可能需要定制ZuulException.响应中的错误信息或状态代码,Zuul过滤器就来帮忙了。在下一节中,我们将讨论如何扩展Zuul的错误过滤器并定制ZuulException.。
3. Customizing Zuul Exceptions
3.定制Zuul例外情况
The starter pack for spring-cloud-starter-netflix-zuul includes three types of filters: pre, post, and error filters. Here, we’ll take a deep dive into error filters and explore the customization of the Zuul error filter dubbed SendErrorFilter.
spring-cloud-starter-netflix-zuul的启动包包括三种类型的过滤器。pre、post以及错误过滤器。在这里,我们将深入了解错误过滤器,并探讨被称为SendErrorFilter的Zuul错误过滤器的定制。
First, we’ll disable the default SendErrorFilter that is configured automatically. This allows us not to worry about the order of execution as this is the only Zuul default error filter. Let’s add the property in application.yml to disable it:
首先,我们将禁用自动配置的默认SendErrorFilter。这使我们不必担心执行的顺序,因为这是唯一的Zuul默认错误过滤器。让我们在application.yml中添加该属性来禁用它。
zuul:
SendErrorFilter:
post:
disable: true
Now, let’s write a custom Zuul error filter called CustomZuulErrorFilter that throws a custom exception if the underlying service is unavailable:
现在,让我们写一个自定义的Zuul错误过滤器,称为CustomZuulErrorFilter,如果底层服务不可用,则抛出一个自定义异常。
public class CustomZuulErrorFilter extends ZuulFilter {
}
This custom filter needs to extend com.netflix.zuul.ZuulFilter and override a few of its methods.
这个自定义过滤器需要扩展com.netflix.zuul.ZuulFilter,并重写它的一些方法.。
First, we have to override the filterType() method and return the type as an “error”. This is because we want to configure the Zuul filter for the error filter type:
首先,我们必须覆盖filterType()方法,并将该类型返回为“error”。这是因为我们要为错误过滤器类型配置Zuul过滤器。
@Override
public String filterType() {
return "error";
}
After that, we override filterOrder() and return -1, so that the filter is the first one in the chain:
之后,我们覆盖filterOrder(),并返回-1,,这样,过滤器就是链中的第一个。
@Override
public int filterOrder() {
return -1;
}
Then, we override the shouldFilter() method and return true unconditionally as we want to chain this filter in all cases:
然后,我们覆盖shouldFilter()方法,并无条件地返回true,因为我们希望在所有情况下都能连锁这个过滤器。
@Override
public boolean shouldFilter() {
return true;
}
Finally, let’s override the run() method:
最后,让我们覆盖run()方法。
@Override
public Object run() {
RequestContext context = RequestContext.getCurrentContext();
Throwable throwable = context.getThrowable();
if (throwable instanceof ZuulException) {
ZuulException zuulException = (ZuulException) throwable;
if (throwable.getCause().getCause().getCause() instanceof ConnectException) {
context.remove("throwable");
context.setResponseBody(RESPONSE_BODY);
context.getResponse()
.setContentType("application/json");
context.setResponseStatusCode(503);
}
}
return null;
}
Let’s break this run() method down to understand what it’s doing. First, we obtain the instance of the RequestContext. Next, we verify whether throwable obtained from RequestContext is an instance of ZuulException. Then, we check if the cause of the nested exception in throwable is an instance of ConnectException. Finally, we’ve set the context with custom properties of the response.
让我们把这个run()方法分解一下,以了解它在做什么。首先,我们获得RequestContext的实例。接下来,我们验证从RequestContext获得的throwable是否是ZuulException的一个实例。然后,我们检查throwable中嵌套异常的原因是否是ConnectException的一个实例。最后,我们用响应的自定义属性来设置上下文。
Note that before setting the custom response, we clear the throwable from the context so that it prevents further error handling in follow-up filters.
请注意,在设置自定义响应之前,我们从上下文中清除throwable,这样可以防止后续过滤器的进一步错误处理。
In addition, we can also set a custom exception inside our run() method that can be handled by the subsequent filters:
此外,我们还可以在我们的run()方法里面设置一个自定义的异常,可以由后续的过滤器来处理。
if (throwable.getCause().getCause().getCause() instanceof ConnectException) {
ZuulException customException = new ZuulException("", 503, "Service Unavailable");
context.setThrowable(customException);
}
The above snippet will log the stack trace and proceed to the next filters.
上面的片段将记录堆栈跟踪,并继续进行下一个过滤器。
Moreover, we can modify this example to handle multiple exceptions inside ZuulFilter.
此外,我们可以修改这个例子来处理ZuulFilter.内的多个异常。
4. Testing Custom Zuul Exceptions
4.测试自定义Zuul异常
In this section, we’ll test the custom Zuul exceptions in our CustomZuulErrorFilter.
在本节中,我们将测试我们的CustomZuulErrorFilter中的自定义Zuul异常。
Assuming there is a ConnectException, the output of the above example in the response of Zuul API would be:
假设有一个ConnectException,上述例子在Zuul API的响应中的输出将是。
{
"timestamp": "2022-01-23T23:10:25.584791Z",
"status": 503,
"error": "Service Unavailable"
}
Furthermore, we can always change the default Zuul error forwarding path /error by configuring the error.path property in the application.yml file.
此外,我们总是可以通过配置error.path属性在application.yml文件中改变默认的Zuul错误转发路径/error。
Now, let’s validate it through some test cases:
现在,让我们通过一些测试案例来验证它。
@Test
public void whenSendRequestWithCustomErrorFilter_thenCustomError() {
Response response = RestAssured.get("http://localhost:8080/foos/1");
assertEquals(503, response.getStatusCode());
}
In the above test scenario, the route for /foos/1 is kept down intentionally, resulting in java.lang.ConnectException. As a result, our custom filter will then intercept and respond with 503 status.
在上述测试场景中,/foos/1的路由被故意保持关闭,导致java.lang.ConnectException。因此,我们的自定义过滤器将拦截并响应503状态。
Now, let’s test this without registering a custom error filter:
现在,让我们在不注册自定义错误过滤器的情况下测试一下。
@Test
public void whenSendRequestWithoutCustomErrorFilter_thenError() {
Response response = RestAssured.get("http://localhost:8080/foos/1");
assertEquals(500, response.getStatusCode());
}
Executing the above test case without registering the custom error filter results in Zuul responding with status 500.
在没有注册自定义错误过滤器的情况下执行上述测试案例,Zuul的响应状态为500。
5. Conclusion
5.总结
In this tutorial, we’ve learned about the hierarchy of error handling and delved into configuring a custom Zuul error filter in a Spring Zuul application. This error filter provided an opportunity to customize the response body as well as the response code. As usual, the sample code is available over on GitHub.
在本教程中,我们已经了解了错误处理的层次结构,并深入研究了在Spring Zuul应用程序中配置自定义Zuul错误过滤器。这个错误过滤器提供了一个自定义响应体以及响应代码的机会。像往常一样,样本代码可在GitHub上获得。