Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

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.

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

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:

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:

public class CustomZuulErrorFilter extends ZuulFilter {
}

This custom filter needs to extend com.netflix.zuul.ZuulFilter 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:

@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:

@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:

@Override
public boolean shouldFilter() {
    return true;
}

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

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

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

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:

{
    "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:

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

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.

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.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – Microservices (eBook) (cat=Cloud/Spring Cloud)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.