Customizing Zuul Exceptions – 定制Zuul例外情况

最后修改: 2022年 2月 8日

1. Overview


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.


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:



Customizing Zuul Exceptions


Zuul displays the following error response when there is a ZuulException:


    "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.


3. Customizing Zuul Exceptions


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.


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:


      disable: true

Now, let’s write a custom Zuul error filter called CustomZuulErrorFilter that throws a custom exception if the underlying service is unavailable:


public class CustomZuulErrorFilter extends ZuulFilter {

This custom filter needs to extend and override a few of its methods.


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:


public String filterType() {
    return "error";

After that, we override filterOrder() and return -1, so that the filter is the first one in the chain:


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:


public boolean shouldFilter() {
    return true;

Finally, let’s override the run() method:


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) {
    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.


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.


In addition, we can also set a custom exception inside our run() method that can be handled by the subsequent filters:


if (throwable.getCause().getCause().getCause() instanceof ConnectException) {
    ZuulException customException = new ZuulException("", 503, "Service Unavailable");

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.


4. Testing Custom Zuul Exceptions


In this section, we’ll test the custom Zuul exceptions in our CustomZuulErrorFilter.


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.


Now, let’s validate it through some test cases:


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.


Now, let’s test this without registering a custom error filter:


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.


5. Conclusion


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上获得