Sub topic 2
What Spring Boot does by default
This chapter covers what a Spring Boot web application does with an exception you never handled. You should already be able to write a @RestController and run it with Maven or Gradle. You should also know that an unchecked exception thrown in a controller method is not caught by the method itself. The examples assume Spring Boot 3.x with Spring MVC (the servlet stack) and the embedded Tomcat that spring-boot-starter-web brings in.
Knowing the default behavior matters for two reasons. It is what your API returns today if you write no error code. It is also the fallback that every later chapter builds on, because anything your own handlers do not catch ends up here.
Where the default behavior comes from
Spring Boot's ErrorMvcAutoConfiguration registers three pieces when it finds a servlet web application:
BasicErrorController, a controller mapped to/error.DefaultErrorAttributes, which builds the map of fields (status, error, path and so on) that describes a failure.- An error page registration with the servlet container. It tells Tomcat to forward any response with an error status to
/error.
Tomcat, not Spring, does the forwarding. Spring MVC marks a request as failed, the container sees the error status, and it dispatches the same request internally to /error. BasicErrorController then renders the body.
The /error path can be changed with server.error.path. The whole mechanism can be replaced by declaring your own bean that implements ErrorController. Most projects never need either.
Following one failing request
The diagram shows what happens when a controller method throws an exception that nothing handles.
Between the controller and the container, DispatcherServlet asks a chain of exception resolvers whether any of them can turn the exception into a response. Some resolvers handle Spring's own exceptions, such as a missing request parameter, and mark the response with a status like 400 using sendError. A plain IllegalStateException matches none of them. It propagates out of the servlet, Tomcat sets the status to 500, and the forward to /error happens. A later chapter looks at the resolver chain in detail. For now, what matters is that both a resolved error (sendError) and an unresolved exception end at /error.
A minimal app to observe it
This small application has two endpoints. One throws an exception on purpose. The other takes a typed request parameter, so you can trigger a framework-generated 400.
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@RestController
@RequestMapping("/demo")
class DemoController {
@GetMapping("/boom")
String boom() {
throw new IllegalStateException("connection to db-internal-7 failed");
}
@GetMapping("/echo")
String echo(@RequestParam int n) {
return "n=" + n;
}
}Start it and call it with curl. The -i flag prints the status line and headers.
curl -i http://localhost:8080/demo/boom
curl -i "http://localhost:8080/demo/echo?n=abc"
curl -i http://localhost:8080/demo/nothing-hereThe first call returns something like this:
{
"timestamp": "2026-12-01T10:14:12.453+00:00",
"status": 500,
"error": "Internal Server Error",
"path": "/demo/boom"
}The second call returns the same shape with "status": 400 and "error": "Bad Request". The third returns 404 and "error": "Not Found". In all three, the message passed to the exception (connection to db-internal-7 failed) does not appear. That is deliberate and is covered in the next section.
What the JSON contains
DefaultErrorAttributes can produce more fields than the example shows. Boot decides which ones to include based on server.error.* properties.
| Field | Meaning | Included by default |
|---|---|---|
| `timestamp` | Time the error was recorded | Yes |
| `status` | HTTP status code | Yes |
| `error` | Reason phrase for the status, such as `Not Found` | Yes |
| `path` | Request path that failed | Yes |
| `message` | The exception message | No. It is empty or absent depending on the Boot version. |
| `errors` | Binding or validation errors | No |
| `exception` | Exception class name | No |
| `trace` | Full stack trace | No |
Before Spring Boot 2.3, message, exception and trace were more liberally available, and the message was always sent. Boot 2.3 hid the message, the stack trace and binding errors unless you opted in. Boot 3 keeps those defaults. If you upgrade an old project, expect clients that read message to see an empty value.
Changing these defaults is a separate topic, covered in the next chapter.
HTML or JSON
BasicErrorController has two handler methods for /error. One produces text/html and renders an error view. The other has no produces restriction and returns the attribute map as JSON. Spring MVC chooses between them using the request's Accept header.
| Client | Typical Accept header | Result |
|---|---|---|
| Browser address bar | `text/html,application/xhtml+xml,...` | HTML error view |
| curl, most HTTP libraries | `*/*` | JSON |
| Fetch or axios asking for JSON | `application/json` | JSON |
If a browser requests /demo/boom, it gets the Whitelabel Error Page, which is a plain HTML page with the status and reason. This is why a REST API can look fine in curl and different in a browser. Both responses come from the same error, rendered by two methods.
The Whitelabel page is on by default. Setting server.error.whitelabel.enabled=false turns off Boot's own page. The container's own error page then takes over, and Tomcat's page can reveal the server product and version. Prefer providing your own view.
Custom error pages by status
For HTML clients you can replace the Whitelabel page without writing a controller. Boot looks for a view named after the status code in two places:
- A template under
src/main/resources/templates/error/, such as404.html, if a template engine like Thymeleaf is on the classpath. - A static file under
src/main/resources/static/error/, such as404.html.
A file named 5xx.html matches any 500-series status, and 4xx.html matches the 400 series. An exact code such as 404.html takes precedence over 4xx.html. These pages only affect the HTML branch. JSON clients still get the attribute map.
Where the defaults fall short for an API
The default response is safe but thin. These are the gaps that the rest of the tutorial fills:
- No explanation for the client. A 400 for a bad request parameter says
Bad Requestand nothing else. The client cannot tell which parameter was wrong. - Unhandled domain failures become 500. If your service throws an exception meaning "order not found", the default maps it to 500, which tells the client the server is broken when the request was simply wrong.
- No stable error code. There is no field a client can switch on to tell one failure from another, apart from the HTTP status.
- A shape that differs from your own errors. Once you add handlers that return a different body, clients see two formats, one from your handlers and one from
/error. - Framework-dependent fields. The set of fields comes from Boot and has changed across versions. Clients that depend on it break when you upgrade.
Common errors
/errorblocked by Spring Security. The forward to/erroris a new dispatch, and Spring Security 6 applies authorization to it. If/errorrequires authentication, an unauthenticated client that triggered a 404 or 400 sees 401 or 403 instead, and the real cause is hidden. Permit/errorexplicitly for all callers, or handle exceptions inside MVC so the forward never happens.- Expecting the controller's exception message in the body. With the defaults, the message is not sent. Use a handler or the
server.error.include-messageproperty deliberately. - Filters that throw. An exception thrown in a servlet filter happens before
DispatcherServlet. It still reaches/errorthrough the container, but handlers you write later for controllers will not see it. - Testing with
MockMvcand expecting/error.MockMvcdoes not run a real servlet container, so it does not perform the forward. A request that fails without a handler shows the status, but the JSON body fromBasicErrorControlleris absent. Use a full-server test (@SpringBootTestwith a random port) to see the real default body.
Exercise
A request to GET /demo/boom fails with an uncaught IllegalStateException("db password is wrong"). With default Spring Boot 3 settings and no DevTools, what status does curl see, which component produces the body, and does the body contain the text "db password is wrong"?
Show answer
curl sees status 500. The DispatcherServlet finds no exception resolver that handles the exception, so it propagates to Tomcat, which forwards the request to /error, where BasicErrorController renders the JSON. Because server.error.include-message defaults to never, the body contains timestamp, status, error and path but not the exception text. The text appears only in the server log.
Exercise
Why can the same failing endpoint show a Whitelabel HTML page in a browser and JSON in curl, and what would you change to stop Boot's HTML page from being used?
Show answer
BasicErrorController has one method that produces text/html and another that returns JSON, and the Accept header picks between them. Browsers ask for text/html, while curl sends */*. To avoid Boot's own page, add a custom error/4xx.html or error/5xx.html view, or set server.error.whitelabel.enabled=false and provide your own error handling. Setting the property alone falls back to the container's page.