Home Java Custom Error Pages in Spring Boot: Mastering Whitelabel ErrorController
Intermediate 5 min · July 14, 2026

Custom Error Pages in Spring Boot: Mastering Whitelabel ErrorController

Learn how to replace the default Whitelabel error page in Spring Boot with custom error pages using ErrorController, HTTP status handling, and production-ready templates..

N
Naren Founder & Principal Engineer

20+ years shipping production Java in banking & fintech. Drawn from code that ran under real load.

Follow
Production
production tested
July 15, 2026
last updated
2,398
articles · all by Naren
Before you start⏱ 15-20 min read
  • Java 17+ installed
  • Spring Boot 3.2+ project with spring-boot-starter-web
  • Basic understanding of Spring MVC and exception handling
 ● Production Incident 🔎 Debug Guide ⚙ Triage Commands
Quick Answer

• Spring Boot's default Whitelabel error page is a generic fallback that should be replaced for production. • You can customize error pages by implementing ErrorController or using error templates in resources/templates/error/. • For REST APIs, return JSON error responses instead of HTML. • Always include meaningful HTTP status codes, error messages, and correlation IDs. • Test error pages with real client scenarios, not just browser navigation.

✦ Definition~90s read
What is Custom Error Pages in Spring Boot?

Custom error pages are user-facing or API responses that replace the default Whitelabel error page in Spring Boot, providing context-specific error information based on the HTTP status code and exception type.

Imagine your application is a restaurant.
Plain-English First

Imagine your application is a restaurant. The Whitelabel error page is like a generic 'We're closed' sign when something goes wrong. Custom error pages are like a polite waiter who explains the specific problem (e.g., 'We're out of steak, but here's a menu with alternatives') and points you to the manager (support) if needed.

⚙ Browser compatibility
Latest versions — ✓ supported
ChromeFirefoxSafariEdge

Every Spring Boot developer has seen it: the stark white page with black text saying 'Whitelabel Error Page' followed by a generic status code and a stack trace snippet. It's the default error view when something goes wrong — and it's a security nightmare for production. Not only does it expose internal implementation details (like class names and line numbers), but it also provides zero user guidance. In this article, we'll tear down that default and build a robust custom error handling system. We'll cover the ErrorController interface, template-based error pages for server-side rendered apps, and JSON error responses for REST APIs. I'll show you how to handle specific HTTP status codes (404, 500, 403) with tailored pages, log errors with correlation IDs, and avoid common pitfalls like infinite redirect loops. By the end, you'll have a production-ready error handling setup that's both user-friendly and developer-friendly. This is intermediate territory — you should already know Spring Boot basics, but we'll dive deep into the mechanics.

Understanding the Whitelabel Error Page

The Whitelabel error page is Spring Boot's fallback when no custom error handling is configured. It's generated by the BasicErrorController (registered automatically via @ConditionalOnMissingBean). The page shows the HTTP status code, the error message (if available), and a stack trace snippet. While convenient for development, it's unsuitable for production because it exposes internal details and provides no user guidance. The default behavior is controlled by server.error.whitelabel.enabled=true. When disabled, Spring Boot looks for a template in resources/templates/error/ matching the status code (e.g., 404.html, 5xx.html). The key interface is ErrorController, which has a single method getErrorPath() (deprecated in 2.3+) — now you implement ErrorController and map a custom endpoint. The default BasicErrorController returns a ModelAndView with attributes like status, error, message, timestamp, trace, path. You can override this by providing your own @Controller that implements ErrorController.

DefaultErrorController.javaJAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import jakarta.servlet.http.HttpServletRequest;

@Controller
public class CustomErrorController implements ErrorController {

    @RequestMapping("/error")
    public String handleError(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute(
            "jakarta.servlet.error.status_code");
        if (statusCode != null) {
            if (statusCode == 404) {
                return "error/404";
            } else if (statusCode == 403) {
                return "error/403";
            } else if (statusCode >= 500) {
                return "error/5xx";
            }
        }
        return "error/generic";
    }

    // Override getErrorPath() is no longer needed in Spring Boot 3.x
}
Output
When a 404 occurs, the controller returns the view name "error/404", which resolves to templates/error/404.html.
⚠ Don't Rely on Default Error Path
📊 Production Insight
In production, always disable server.error.whitelabel.enabled=false to avoid accidental fallback. Then implement your own controller to ensure consistent behavior across all environments.
🎯 Key Takeaway
The default Whitelabel page is a development convenience, not a production solution. Replace it with a custom ErrorController that routes to specific templates based on status codes.

What the Official Docs Won't Tell You

The official Spring Boot documentation covers the basics of custom error pages but glosses over critical production details. First, the BasicErrorController doesn't handle Accept headers well — it returns HTML for everything unless you override it. For REST APIs, you must check the request's Accept header or use @RequestMapping(produces = "application/json"). Second, error handling for async requests (e.g., @Async or CompletableFuture) is broken by default — exceptions thrown in async methods won't trigger the error controller unless you configure an AsyncExceptionHandler. Third, the trace attribute in the error model can include sensitive data like SQL queries or file paths; always strip it in production. Fourth, if you use Spring Security, the error controller might not be accessible for unauthenticated users — you need to permit access to /error in your security config. Finally, the order of error handling matters: @ExceptionHandler in controllers takes precedence over the error controller, which only catches unhandled exceptions. This can lead to inconsistent error formats if you mix both approaches.

ErrorControllerWithAcceptHeader.javaJAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import jakarta.servlet.http.HttpServletRequest;

@Controller
public class SmartErrorController implements ErrorController {

    @RequestMapping(value = "/error", produces = MediaType.TEXT_HTML_VALUE)
    public String handleErrorHtml(HttpServletRequest request) {
        Integer status = (Integer) request.getAttribute(
            "jakarta.servlet.error.status_code");
        if (status == 404) return "error/404";
        if (status == 403) return "error/403";
        return "error/5xx";
    }

    @RequestMapping(value = "/error", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Map<String, Object>> handleErrorJson(HttpServletRequest request) {
        Integer status = (Integer) request.getAttribute(
            "jakarta.servlet.error.status_code");
        Map<String, Object> body = new HashMap<>();
        body.put("status", status);
        body.put("error", HttpStatus.valueOf(status).getReasonPhrase());
        body.put("message", request.getAttribute("jakarta.servlet.error.message"));
        body.put("path", request.getAttribute("jakarta.servlet.error.request_uri"));
        body.put("timestamp", Instant.now().toString());
        return ResponseEntity.status(status).body(body);
    }
}
Output
For a browser request (Accept: text/html), the controller returns an HTML view. For an API client (Accept: application/json), it returns a JSON response with status, error, message, path, and timestamp.
🔥Async Exception Handling Gotcha
📊 Production Insight
In a microservices architecture, standardize error response format across all services using a shared DTO. Include a correlation ID (from the request header) to trace errors across services.
🎯 Key Takeaway
The official docs don't cover Accept header differentiation, async error handling, or security context. Always test error responses with both browser and API clients.

Setting Up Custom Error Templates

To serve custom HTML error pages, create Thymeleaf (or FreeMarker) templates in src/main/resources/templates/error/. Spring Boot automatically resolves views based on the status code: 404.html for 404, 5xx.html for any 5xx, and error.html as a fallback. The template can access model attributes like status, error, message, path, and timestamp. For a more dynamic approach, use a single template that reads the status code and displays appropriate content. Use Thymeleaf's th:if to conditionally show different sections. For static resources (CSS, images), place them in src/main/resources/static/ and reference them with relative paths. Example: a 404 page with a friendly message and a link to the home page. For 5xx pages, avoid showing stack traces; instead, display a generic apology and a support contact. You can also use server.error.include-stacktrace=never in application.properties to globally disable stack traces in error responses.

404.htmlHTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Page Not Found</title>
    <link rel="stylesheet" th:href="@{/css/error.css}" />
</head>
<body>
    <div class="error-container">
        <h1>404 - Page Not Found</h1>
        <p th:text="${message} ?: 'The page you requested does not exist.'"></p>
        <p>Path: <span th:text="${path}">/unknown</span></p>
        <a th:href="@{/}">Go to Home</a>
    </div>
</body>
</html>
Output
When a 404 occurs, the browser renders this HTML page with the error message (if available) and the original request path.
Try it live
💡Use a Single Fallback Template
📊 Production Insight
For high-traffic sites, consider caching error pages using Spring's cache abstraction or a CDN. Error pages are often static and can be served quickly without hitting the application server.
🎯 Key Takeaway
Place error templates in /templates/error/ and use Thymeleaf to access model attributes. Disable stack traces in production via server.error.include-stacktrace=never.

Handling REST API Errors with JSON

For REST APIs, returning HTML error pages is useless. Instead, return a consistent JSON error response. The approach depends on whether you use @RestControllerAdvice or the ErrorController. The @RestControllerAdvice with @ExceptionHandler is ideal for known exceptions (like ResourceNotFoundException). For unhandled exceptions, the ErrorController catches them. To unify both, create a custom error response DTO and use it in both places. The DTO should include: status (HTTP status code), error (reason phrase), message (human-readable), path (request URI), timestamp, and traceId (for debugging). Use UUID.randomUUID() for trace IDs. For validation errors (400 Bad Request), include a errors field with field-level details. In Spring Boot 3.x, you can use ProblemDetail from RFC 7807, but it's less flexible. I prefer a custom DTO for full control. Remember to set the Content-Type header to application/problem+json if using ProblemDetail, or just application/json.

ErrorResponseDto.javaJAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.time.Instant;
import java.util.List;

public class ErrorResponseDto {
    private int status;
    private String error;
    private String message;
    private String path;
    private Instant timestamp;
    private String traceId;
    private List<FieldError> fieldErrors;

    // Constructors, getters, setters
    public ErrorResponseDto(int status, String error, String message, String path) {
        this.status = status;
        this.error = error;
        this.message = message;
        this.path = path;
        this.timestamp = Instant.now();
        this.traceId = UUID.randomUUID().toString();
    }

    public static class FieldError {
        private String field;
        private String message;
        // constructor, getters
    }
}
Output
This DTO provides a standardized error response structure that can be used across all error handlers, ensuring consistency for API clients.
⚠ Avoid Leaking Stack Traces in JSON
📊 Production Insight
In a microservices environment, include the service name and version in the error response to help with debugging. Use a shared library for the ErrorResponseDto across all services.
🎯 Key Takeaway
For REST APIs, return JSON error responses with a consistent DTO that includes status, message, path, timestamp, and traceId. Avoid stack traces in the response.

Advanced: Using ErrorAttributes for Fine-Grained Control

Spring Boot's DefaultErrorAttributes provides model attributes for error views. You can customize it by creating a bean that implements ErrorAttributes or extends DefaultErrorAttributes. Override getErrorAttributes() to add, remove, or modify attributes. For example, you might want to add a supportEmail attribute or remove the trace attribute. The ErrorAttributes interface has two methods: getErrorAttributes(WebRequest, ErrorAttributeOptions) and getError(WebRequest). The ErrorAttributeOptions lets you include or exclude stack trace, message, and binding errors. In production, always exclude stack trace. You can also add custom attributes like environment (from @Value("${spring.profiles.active}")) or appVersion. This is especially useful when you want to include business-specific error codes (e.g., ERR-001 for validation errors). The ErrorAttributes bean is automatically picked up by the BasicErrorController (or your custom controller).

CustomErrorAttributes.javaJAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.WebRequest;
import java.util.Map;

@Component
public class CustomErrorAttributes extends DefaultErrorAttributes {

    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest,
                                                  ErrorAttributeOptions options) {
        Map<String, Object> attrs = super.getErrorAttributes(webRequest, options);
        // Remove stack trace
        attrs.remove("trace");
        // Add custom attributes
        attrs.put("supportEmail", "support@example.com");
        attrs.put("environment", System.getProperty("spring.profiles.active"));
        attrs.put("errorCode", "ERR-" + attrs.get("status"));
        return attrs;
    }
}
Output
The error model now includes supportEmail, environment, and errorCode, while the trace attribute is removed. These attributes are available in Thymeleaf templates or JSON responses.
🔥ErrorAttributeOptions in Spring Boot 3.x
📊 Production Insight
Use ErrorAttributes to inject environment-specific information (e.g., 'staging' vs 'production') to help support teams quickly identify the context of an error.
🎯 Key Takeaway
Customize ErrorAttributes to add business-specific fields (like error codes, support email) and remove sensitive attributes like stack traces. This gives you fine-grained control over error responses.

Testing Custom Error Pages

Testing error pages is often neglected, leading to broken error handling in production. Use Spring Boot's MockMvc to simulate errors and verify the response. For HTML pages, check the status code and the presence of expected text (e.g., "Page Not Found"). For JSON responses, verify the structure and fields. Use @WebMvcTest with your error controller. To simulate a 404, use mockMvc.perform(get("/nonexistent")). For 500, you can throw an exception from a test endpoint. Also test the Accept header differentiation: send a request with Accept: application/json and verify JSON response. For integration tests, use @SpringBootTest with a random port and TestRestTemplate. Remember to test error pages for authenticated and unauthenticated users separately, as security filters might interfere. Use @WithMockUser for authenticated scenarios. Also test that static resources (CSS, images) are loaded correctly on error pages.

ErrorControllerTest.javaJAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@WebMvcTest(CustomErrorController.class)
class ErrorControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    void test404ReturnsCustomPage() throws Exception {
        mockMvc.perform(get("/error")
                .requestAttr("jakarta.servlet.error.status_code", 404))
                .andExpect(status().isOk())
                .andExpect(view().name("error/404"))
                .andExpect(content().string(containsString("Page Not Found")));
    }

    @Test
    void testJsonErrorForApiClient() throws Exception {
        mockMvc.perform(get("/error")
                .requestAttr("jakarta.servlet.error.status_code", 500)
                .accept("application/json"))
                .andExpect(status().isInternalServerError())
                .andExpect(jsonPath("$.status").value(500))
                .andExpect(jsonPath("$.traceId").exists());
    }
}
Output
The test verifies that a 404 returns the correct view name and contains expected text. The JSON test checks the status and traceId fields.
💡Test with Real Client Headers
📊 Production Insight
Include error page tests in your CI/CD pipeline. A broken error page can be worse than no error page — it can confuse users and hide the real problem.
🎯 Key Takeaway
Test error pages with MockMvc for unit tests and TestRestTemplate for integration tests. Verify both HTML and JSON responses, and test with different Accept headers.

Common Pitfalls and How to Avoid Them

One common pitfall is infinite redirect loops. If your error controller redirects to another page that also triggers an error, you get a loop. Always return a view or response directly from the error controller, never redirect. Another pitfall is forgetting to permit access to /error in Spring Security. If your security config requires authentication for all endpoints, the error page won't be accessible for unauthenticated users, causing a 403 instead of the intended error page. Add requestMatchers("/error").permitAll() to your security config. A third pitfall is mixing @ExceptionHandler and ErrorController inconsistently. If you use @ExceptionHandler for some exceptions and the error controller for others, ensure both return the same format (HTML or JSON). Otherwise, clients get different response structures depending on the error type. Finally, don't forget to disable the Whitelabel page explicitly: server.error.whitelabel.enabled=false. Otherwise, if your custom controller fails, Spring Boot falls back to the default.

SecurityConfig.javaJAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/error").permitAll()
                .anyRequest().authenticated()
            )
            .formLogin();
        return http.build();
    }
}
Output
The /error endpoint is now accessible to unauthenticated users, allowing them to see custom error pages instead of being redirected to login.
⚠ Infinite Redirect Loop Detection
📊 Production Insight
Add a log statement in your error controller to track how many times it's invoked per request. A high count indicates a loop or misconfiguration.
🎯 Key Takeaway
Avoid redirects in error controllers, permit access to /error in security config, and unify error formats across @ExceptionHandler and ErrorController.

Production-Ready Error Handling with Logging and Monitoring

In production, error pages are not just for users — they're also a source of monitoring data. Every time an error page is served, log the event with a structured format (e.g., JSON logs). Include the traceId, status code, path, and the exception class (if available). Use a logging framework like Logback with a JSON encoder. For monitoring, expose error metrics via Micrometer (part of Spring Boot Actuator). Create a custom counter for each status code family (4xx, 5xx). For example, Counter.builder("http.server.errors").tag("status", "5xx").register(meterRegistry). You can then alert on spikes in 5xx errors. Also, consider using Spring Boot Admin or a dedicated APM tool to track error rates. For critical errors, send notifications to a Slack channel or PagerDuty. The error controller is an ideal place to add this instrumentation because it's the last line of defense.

MonitoredErrorController.javaJAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Controller
public class MonitoredErrorController implements ErrorController {

    private static final Logger log = LoggerFactory.getLogger(MonitoredErrorController.class);
    private final Counter errorCounter;

    public MonitoredErrorController(MeterRegistry meterRegistry) {
        this.errorCounter = Counter.builder("http.server.errors")
                .description("Total HTTP server errors")
                .register(meterRegistry);
    }

    @RequestMapping("/error")
    public String handleError(HttpServletRequest request) {
        Integer status = (Integer) request.getAttribute(
            "jakarta.servlet.error.status_code");
        String path = (String) request.getAttribute(
            "jakarta.servlet.error.request_uri");
        
        log.warn("Error {} on path {} - traceId: {}", status, path,
            UUID.randomUUID().toString());
        errorCounter.increment();
        
        if (status == 404) return "error/404";
        if (status == 403) return "error/403";
        return "error/5xx";
    }
}
Output
Each error increments a Micrometer counter and logs a structured warning with status, path, and traceId. This data can be used for dashboards and alerts.
🔥Structured Logging with Logback
📊 Production Insight
Set up a Grafana dashboard showing error rates by status code and path. Alert when 5xx errors exceed a threshold (e.g., 1% of total requests).
🎯 Key Takeaway
Instrument your error controller with logging and metrics. Use Micrometer counters for error rates and structured logs with traceIds for debugging.
● Production incidentPOST-MORTEMseverity: high

The Whitelabel Leak: How a Default Error Page Exposed Our Internal API

Symptom
Users reported seeing a white page with a stack trace containing internal class names and file paths after a database timeout.
Assumption
The team assumed error pages were only for browser-based errors and didn't apply to REST API responses.
Root cause
Spring Boot's default error controller was returning HTML with full stack traces for all 5xx errors, even for API calls expecting JSON.
Fix
Implemented a custom ErrorController that returns JSON for requests with 'Accept: application/json' header and HTML for browsers, with stack traces stripped in both cases.
Key lesson
  • Never rely on the default Whitelabel page in production — it's a security risk.
  • Always differentiate between human-facing and API error responses.
  • Use correlation IDs in error responses to trace issues without exposing internals.
Production debug guideStep-by-step guide to diagnose and fix error page issues4 entries
Symptom · 01
Users see default Whitelabel page despite custom setup
Fix
Check if server.error.whitelabel.enabled is set to false. Also verify your ErrorController is annotated with @Controller and mapped to /error.
Symptom · 02
Error page shows blank or missing CSS
Fix
Ensure static resources (CSS, images) are in src/main/resources/static/ and paths in templates are correct. Use Thymeleaf's @{/css/error.css} syntax.
Symptom · 03
API clients get HTML instead of JSON
Fix
Check the Accept header in the request. Your ErrorController must check for application/json and return ResponseEntity. Use Postman to test with different headers.
Symptom · 04
Infinite redirect loop on error pages
Fix
Remove any redirect: prefix in your error controller. Use return "error/404" instead of return "redirect:/error". Check for filters that might redirect.
★ Quick Debug Cheat Sheet for Custom Error PagesCommon symptoms and immediate actions for error page issues
Whitelabel page still showing
Immediate action
Set server.error.whitelabel.enabled=false in application.properties
Commands
grep -r 'whitelabel' src/main/resources/application.properties
curl -I http://localhost:8080/nonexistent
Fix now
Add the property and restart the application
Error page returns 403 for unauthenticated users+
Immediate action
Add requestMatchers("/error").permitAll() to SecurityConfig
Commands
curl -v http://localhost:8080/error
Check Spring Security logs for access denied
Fix now
Update SecurityFilterChain and restart
JSON error response has extra fields+
Immediate action
Check CustomErrorAttributes for unwanted attributes
Commands
curl -H "Accept: application/json" http://localhost:8080/error
Check logs for error attributes map
Fix now
Override getErrorAttributes and remove unwanted fields
FeatureDefault Whitelabel PageCustom ErrorController
SecurityExposes stack traces and internalsStrips sensitive data, uses traceId
User ExperienceGeneric white pageTailored pages with guidance
API SupportHTML onlyJSON or HTML based on Accept header
CustomizationLimited to propertiesFull control via code and templates
MonitoringNo built-in metricsCan add Micrometer counters and logging
⚙ Quick Reference
8 commands from this guide
FileCommand / CodePurpose
DefaultErrorController.java@ControllerUnderstanding the Whitelabel Error Page
ErrorControllerWithAcceptHeader.java@ControllerWhat the Official Docs Won't Tell You
404.htmlSetting Up Custom Error Templates
ErrorResponseDto.javapublic class ErrorResponseDto {Handling REST API Errors with JSON
CustomErrorAttributes.java@ComponentAdvanced
ErrorControllerTest.java@WebMvcTest(CustomErrorController.class)Testing Custom Error Pages
SecurityConfig.java@ConfigurationCommon Pitfalls and How to Avoid Them
MonitoredErrorController.java@ControllerProduction-Ready Error Handling with Logging and Monitoring

Key takeaways

1
Replace the default Whitelabel error page with a custom ErrorController that handles both HTML and JSON responses based on the Accept header.
2
Use ErrorAttributes to customize error model attributes, adding business-specific fields and removing sensitive data like stack traces.
3
Instrument your error controller with logging and Micrometer metrics for production monitoring and alerting.
INTERVIEW PREP · PRACTICE MODE

Interview Questions on This Topic

Q01JUNIOR
How does Spring Boot's default error handling work, and how would you re...
Q02SENIOR
Explain how you would handle error responses differently for browser use...
Q03SENIOR
How do you ensure that custom error pages are accessible to unauthentica...
Q04SENIOR
Describe a production incident where default error handling caused a sec...
Q01 of 04JUNIOR

How does Spring Boot's default error handling work, and how would you replace it?

ANSWER
Spring Boot automatically configures a BasicErrorController that returns a Whitelabel error page. To replace it, you can either provide custom templates in /templates/error/ (e.g., 404.html) or implement the ErrorController interface and map a controller to /error. The latter gives full control over the response.
FAQ · 4 QUESTIONS

Frequently Asked Questions

01
How do I disable the Whitelabel error page in Spring Boot?
02
Can I use the same error handling for both REST API and web pages?
03
What's the difference between @ExceptionHandler and ErrorController?
04
How do I include a stack trace in error responses for debugging?
N
Naren Founder & Principal Engineer

20+ years shipping production Java in banking & fintech. Drawn from code that ran under real load.

Follow
Verified
production tested
July 15, 2026
last updated
2,398
articles · all by Naren
🔥

That's Spring Boot. Mark it forged?

5 min read · try the examples if you haven't

Previous
How to Change the Default Port and Context Path in Spring Boot
61 / 121 · Spring Boot
Next
Custom Banners in Spring Boot: ASCII Art, Custom Banner Classes, and Profiles