Spring Boot
Error Mapping
Spring Framework
Java Development
Web Services

Spring Boot Disable /error mapping

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Spring Boot automatically registers /error so unhandled exceptions and status failures produce a default response. That behavior is useful during development, but many production systems need strict, custom error contracts. Disabling or replacing the default mapping is mostly about taking ownership of error flow at the framework boundaries.

How Default Error Mapping Works

By default, Spring Boot configures BasicErrorController through ErrorMvcAutoConfiguration. This controller handles failures that were not fully resolved by other handlers and sends either HTML or JSON depending on content negotiation.

That means even if you have @ControllerAdvice, some cases still end up at /error, especially routing errors and container-level failures. If you need complete control, you typically choose one of two approaches:

  • Replace default behavior with your own error controller.
  • Disable error MVC auto configuration and handle failures yourself.

The first approach is safer for most teams because it preserves expected framework flow while giving you custom payloads.

Replace /error With a Custom Controller

A practical pattern is to keep the endpoint but return your own contract. This avoids surprises in filters, proxies, and clients that already expect /error to exist.

java
1package com.example.demo.error;
2
3import jakarta.servlet.http.HttpServletRequest;
4import org.springframework.boot.web.error.ErrorAttributeOptions;
5import org.springframework.boot.web.servlet.error.ErrorAttributes;
6import org.springframework.boot.web.servlet.error.ErrorController;
7import org.springframework.http.HttpStatus;
8import org.springframework.http.ResponseEntity;
9import org.springframework.web.bind.annotation.RequestMapping;
10import org.springframework.web.bind.annotation.RestController;
11import org.springframework.web.context.request.ServletWebRequest;
12
13import java.time.Instant;
14import java.util.Map;
15
16@RestController
17public class ApiErrorController implements ErrorController {
18
19    private final ErrorAttributes errorAttributes;
20
21    public ApiErrorController(ErrorAttributes errorAttributes) {
22        this.errorAttributes = errorAttributes;
23    }
24
25    @RequestMapping("/error")
26    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
27        ServletWebRequest webRequest = new ServletWebRequest(request);
28        Map<String, Object> attrs = errorAttributes.getErrorAttributes(
29            webRequest,
30            ErrorAttributeOptions.of(ErrorAttributeOptions.Include.MESSAGE)
31        );
32
33        int status = (int) attrs.getOrDefault("status", 500);
34        Map<String, Object> body = Map.of(
35            "timestamp", Instant.now().toString(),
36            "status", status,
37            "error", attrs.getOrDefault("error", "Unexpected Error"),
38            "message", attrs.getOrDefault("message", "No detail")
39        );
40
41        return ResponseEntity.status(HttpStatus.valueOf(status)).body(body);
42    }
43}

With this, clients always get predictable JSON instead of default HTML pages.

Disable Whitelabel and Tune Exposure

If your app accidentally returns HTML error pages, disable the whitelabel view and control detail fields.

properties
1server.error.whitelabel.enabled=false
2server.error.include-message=never
3server.error.include-binding-errors=never
4server.error.include-stacktrace=never

These settings do not remove /error, but they reduce leakage of internal details.

When you need detailed responses in non-production profiles, use profile-based configuration instead of global settings.

Full Disable of Error MVC Auto Configuration

If you truly want no Boot error controller at all, exclude auto configuration and provide your own handling stack.

java
1package com.example.demo;
2
3import org.springframework.boot.SpringApplication;
4import org.springframework.boot.autoconfigure.SpringBootApplication;
5import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration;
6
7@SpringBootApplication(exclude = ErrorMvcAutoConfiguration.class)
8public class DemoApplication {
9    public static void main(String[] args) {
10        SpringApplication.run(DemoApplication.class, args);
11    }
12}

Then add explicit exception handlers:

java
1package com.example.demo.error;
2
3import org.springframework.http.HttpStatus;
4import org.springframework.http.ResponseEntity;
5import org.springframework.web.bind.MethodArgumentNotValidException;
6import org.springframework.web.bind.annotation.ExceptionHandler;
7import org.springframework.web.bind.annotation.RestControllerAdvice;
8
9import java.util.Map;
10
11@RestControllerAdvice
12public class ApiExceptionAdvice {
13
14    @ExceptionHandler(MethodArgumentNotValidException.class)
15    public ResponseEntity<Map<String, Object>> handleValidation(MethodArgumentNotValidException ex) {
16        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
17            .body(Map.of("code", "VALIDATION_ERROR", "message", "Request validation failed"));
18    }
19
20    @ExceptionHandler(Exception.class)
21    public ResponseEntity<Map<String, Object>> handleAny(Exception ex) {
22        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
23            .body(Map.of("code", "INTERNAL_ERROR", "message", "Unexpected server error"));
24    }
25}

This route gives maximum control but demands more test coverage because framework fallbacks are removed.

Test Error Behavior End to End

After changes, verify several paths:

  • missing route
  • validation failure
  • uncaught exception
bash
curl -i http://localhost:8080/does-not-exist
curl -i -X POST http://localhost:8080/api/items -H 'Content-Type: application/json' -d '{}'

Also test with Accept: text/html and Accept: application/json to ensure your app does not unexpectedly switch formats.

Common Pitfalls

  • Disabling auto configuration without adding comprehensive global handlers.
  • Returning inconsistent payload shapes between validation and runtime errors.
  • Leaving stack traces enabled in production responses.
  • Assuming @ControllerAdvice covers all container-level error cases.
  • Forgetting content negotiation tests after replacing /error.

Summary

  • Default /error mapping comes from Boot error MVC auto configuration.
  • Replacing /error is usually safer than removing it completely.
  • Use properties to disable whitelabel pages and sensitive detail leakage.
  • Excluding auto configuration requires a robust custom error strategy.
  • Validate error behavior with real HTTP requests and different Accept headers.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.