Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW