Default Spring error responses
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A customer's app asks the ShopLite API for product 99, which does not exist, and the server fails. What does the app actually receive, and what does the server write to its log?
An uncaught exception: a 500 and a stack trace in the log
An uncaught exception is an exception that leaves a controller method with no catch or handler dealing with it. Spring Boot then answers with status 500 Internal Server Error and writes the stack trace to the server log.
ShopLite looks up product 99. The service throws because the product is missing, and nothing catches the exception.
Example 1 · ProductResponse.java, ProductService.java, ProductController.java
Runs in: the errors-lab practice project (Spring Boot 4.1)
// src/main/java/com/shoplite/lab/product/ProductResponse.javapackage com.shoplite.lab.product;
import java.math.BigDecimal;
public record ProductResponse(long id, String sku, String name, BigDecimal price, int stock) {}
// src/main/java/com/shoplite/lab/product/ProductService.javapackage com.shoplite.lab.product;
import java.math.BigDecimal;import java.util.Map;import java.util.Optional;import java.util.concurrent.ConcurrentHashMap;
import org.springframework.stereotype.Service;
@Servicepublic class ProductService {
private final Map<Long, ProductResponse> products = new ConcurrentHashMap<>();
public ProductService() { add(new ProductResponse(1, "MOB-RN13", "Redmi Note 13 5G", new BigDecimal("17999.00"), 40)); add(new ProductResponse(3, "MOB-IP15", "iPhone 15 128GB", new BigDecimal("69900.00"), 8)); add(new ProductResponse(6, "ACC-AD141", "boAt Airdopes 141", new BigDecimal("1299.00"), 120)); }
private void add(ProductResponse product) { products.put(product.id(), product); }
public ProductResponse findById(long id) { return Optional.ofNullable(products.get(id)).orElseThrow(); }}
// src/main/java/com/shoplite/lab/product/ProductController.javapackage com.shoplite.lab.product;
import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;
@RestController@RequestMapping("/api/v1/products")public class ProductController {
private final ProductService productService;
public ProductController(ProductService productService) { this.productService = productService; }
@GetMapping("/{id}") public ProductResponse getProduct(@PathVariable long id) { return productService.findById(id); }}$ curl -i http://localhost:8080/api/v1/products/99
HTTP/1.1 500
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 04:56:44 GMT
Connection: close
{"timestamp":"2026-10-16T04:56:44.685Z","status":500,"error":"Internal Server Error","path":"/api/v1/products/99"}
### html
Server console:
2026-10-16T10:26:44.650+05:30 ERROR 23688 --- [nio-8080-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: java.util.NoSuchElementException: No value present] with root cause
java.util.NoSuchElementException: No value present
at java.base/java.util.Optional.orElseThrow(Optional.java:377) ~[na:na]
at com.shoplite.lab.product.ProductService.findById(ProductService.java:27) ~[!/:0.0.1-SNAPSHOT]
at com.shoplite.lab.product.ProductController.getProduct(ProductController.java:20) ~[!/:0.0.1-SNAPSHOT]
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:580) ~[na:na]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:252) ~[spring-web-7.0.9.jar!/:7.0.9]
...What this code does
- There is no product 99, so
orElseThrow()throwsNoSuchElementException. Nothing catches it, so the client gets 500 and the plain default body. - The console shows
ERROR, the exception and the stack trace. The linesProductService.java:27andProductController.java:20point at the exact place the exception was thrown. Connection: closetells the client that Tomcat closes the connection after a 500. Tomcat 11 also leaves out the reason phrase, so the status line is justHTTP/1.1 500.
Without this answer, the client would wait or see a broken connection. With it, the client at least learns that the server failed, and you can read the cause in the console.
The trouble is that every failure looks the same. A product id that does not exist is the client's mistake, but here it shows up as 500, a server fault, and the log fills with traces for a normal "not found".
The /error endpoint: JSON for API clients, a Whitelabel page for browsers
/error is the internal URL that every failed request is forwarded to. Spring Boot's BasicErrorController answers it with JSON for API clients and the Whitelabel Error Page for browsers.
The same failing request again, asked for the way a browser asks: with an Accept: text/html header.
Example 2 · The same failure seen by a browser
Runs in: the errors-lab practice project (Spring Boot 4.1)
curl -i -H "Accept: text/html" http://localhost:8080/api/v1/products/99HTTP/1.1 500 Content-Type: text/html;charset=UTF-8 Content-Language: en-IN Content-Length: 287 Date: Fri, 16 Oct 2026 04:56:45 GMT Connection: close <html><body><h1>Whitelabel Error Page</h1><p>This application has no explicit mapping for /error, so you are seeing this as a fallback.</p><div id='created'>Fri Oct 16 10:26:45 IST 2026</div><div>There was an unexpected error (type=Internal Server Error, status=500).</div></body></html> ### typo url
What this code does
-H "Accept: text/html"makes curl ask for HTML the way a browser does, so/erroranswers with the Whitelabel page instead of JSON.- Same exception, same status 500, different body: the error reply depends on what the client asked for, not on what failed.
BasicErrorController looks at the request's Accept header. A client that asks for HTML, such as a browser, gets the Whitelabel Error Page: a plain HTML page with "There was an unexpected error". Any other client, such as curl, Postman or a mobile app, gets JSON.
The Whitelabel page is a fallback for apps with no error page of their own. An API never needs it; turn it off with spring.web.error.whitelabel.enabled=false.
Default fields: timestamp, status, error, path
The default error body is the JSON Spring Boot sends for a failed request: timestamp (when it failed, in UTC), status (the HTTP code), error (the standard phrase, such as Not Found) and path (the URL that was called).
Two more failures: a URL that has no controller, and a path variable that is not a number.
Example 3 · Default bodies for a wrong URL and a wrong type
Runs in: the errors-lab practice project (Spring Boot 4.1)
curl -i http://localhost:8080/api/v1/prodctscurl -i http://localhost:8080/api/v1/products/abc$ curl -i http://localhost:8080/api/v1/prodcts
HTTP/1.1 404
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 04:56:45 GMT
{"timestamp":"2026-10-16T04:56:45.618Z","status":404,"error":"Not Found","path":"/api/v1/prodcts"}
### type mismatch
$ curl -i http://localhost:8080/api/v1/products/abc
HTTP/1.1 400
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 04:56:46 GMT
Connection: close
{"timestamp":"2026-10-16T04:56:46.012Z","status":400,"error":"Bad Request","path":"/api/v1/products/abc"}
### error directWhat this code does
/prodcts(a typo) matches no controller, so Spring MVC gives 404.abccannot become thelong id, so it gives 400. Both bodies have the same four fields.- Neither body says what was wrong. A client cannot tell "this URL does not exist" from "this product does not exist", because both would be a bare 404.
The same four fields appear for every kind of failure: an exception in your code (500), a URL with no controller (404) and a bad path variable (400). Spring MVC decides the status for its own exceptions, such as 400 for abc where a long was expected.
What is missing matters too. There is no message saying what went wrong, no list of bad fields and no exception name. Spring Boot hides them on purpose.
Predict the output
Which status does the client get?
Spring Boot has no handlers yet. Pick the status for each request.
Round 1 of 3
GET /api/v1/products/99, and ProductService.findById throws NoSuchElementException.
spring.web.error.include-message and include-stacktrace
spring.web.error.include-message decides whether the error body gets a message field with the exception message. Its twin include-stacktrace does the same for a trace field. Values: never (default), always, on-param.
Start the app with include-message=always for one run and call the same two failing URLs.
Example 4 · Showing the message: spring.web.error.include-message
Runs in: the errors-lab practice project (Spring Boot 4.1)
# Start the app with the setting for this run onlyjava -jar target/errors-lab-0.0.1-SNAPSHOT.jar --spring.web.error.include-message=always# In a second terminalcurl http://localhost:8080/api/v1/products/99curl http://localhost:8080/api/v1/products/abc$ curl http://localhost:8080/api/v1/products/99
{"timestamp":"2026-10-16T05:48:44.912Z","status":500,"error":"Internal Server Error","message":"No value present","path":"/api/v1/products/99"}
$ curl http://localhost:8080/api/v1/products/abc
{"timestamp":"2026-10-16T05:48:45.255Z","status":400,"error":"Bad Request","message":"Method parameter 'id': Failed to convert value of type 'java.lang.String' to required type 'long'; For input string: \"abc\"","path":"/api/v1/products/abc"}What this code does
- A
--name=valueargument after the jar name sets a property for this run only, which is handy for a quick check. The same line inapplication.propertieswould set it for every run. - Now each body has a
messagefield. It is the raw exception message:No value presentis useless to a client, and the second one shows Java type names and internal wording.
Example 5 · Why production hides the stack trace
Runs in: the errors-lab practice project (Spring Boot 4.1)
# App started with --spring.web.error.include-message=always --spring.web.error.include-stacktrace=alwayscurl -s http://localhost:8080/api/v1/products/99 | head -c 420{"timestamp":"2026-10-16T05:49:01.470Z","status":500,"error":"Internal Server Error","trace":"java.util.NoSuchElementException: No value present\r\n\tat java.base/java.util.Optional.orElseThrow(Optional.java:377)\r\n\tat com.shoplite.lab.product.ProductService.findById(ProductService.java:27)\r\n\tat com.shoplite.lab.product.ProductController.getProduct(ProductController.java:20)\r\n\tat java.base/jdk.internal.reflecWhat this code does
head -c 420keeps only the first 420 characters; the fulltracefield is several kilobytes long and lists every frame, including Tomcat and Spring classes with their versions.- Anyone who calls the API can now read your package names (
com.shoplite.lab.product), class names and line numbers. That is why both settings stay atneveroutside your own computer.
on-param adds the field only when the URL has ?message=true or ?trace=true. In Spring Boot 3 these settings were server.error.include-message and server.error.include-stacktrace; Spring Boot 4 renamed them to spring.web.error.*, and the old names no longer do anything.
Keep never in production. A message such as For input string: "abc" or a trace with package names, library versions and line numbers tells an attacker how your server is built, and a user learns nothing useful from it.
Why clients need one predictable error shape
An error shape is the set of fields every error reply carries, with the same meaning for every endpoint and every kind of failure. A client can only handle errors in code when the shape never changes.
Three endpoints of a mixed API, each reporting "not found" in its own way.
Example 6 · src/main/java/com/shoplite/lab/other/MixedErrorsController.java
Runs in: the errors-lab practice project (Spring Boot 4.1)
package com.shoplite.lab.other;
import java.util.Map;
import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RestController;
@RestControllerpublic class MixedErrorsController {
@GetMapping("/api/v1/categories/{id}") public ResponseEntity<Map<String, Object>> category(@PathVariable long id) { return ResponseEntity.notFound().build(); // 404, empty body }
@GetMapping("/api/v1/customers/{id}") public ResponseEntity<Map<String, Object>> customer(@PathVariable long id) { return ResponseEntity.status(HttpStatus.NOT_FOUND) .body(Map.of("msg", "no such customer", "code", 1004)); // 404, made-up body }
@GetMapping("/api/v1/orders/{id}") public ResponseEntity<Map<String, Object>> order(@PathVariable long id) { return ResponseEntity.ok(Map.of("error", true, "reason", "Order not found")); // 200 for an error }}$ curl -i http://localhost:8080/api/v1/categories/99
HTTP/1.1 404
Content-Length: 0
Date: Fri, 16 Oct 2026 04:56:46 GMT
$ curl -i http://localhost:8080/api/v1/customers/99
HTTP/1.1 404
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 04:56:46 GMT
{"msg":"no such customer","code":1004}
$ curl -i http://localhost:8080/api/v1/orders/99
HTTP/1.1 200
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 04:56:47 GMT
{"reason":"Order not found","error":true}
### on-paramWhat this code does
- Each method reports "not found" the way a different developer might:
ResponseEntity.notFound().build()(an empty 404), a made-up{"msg", "code"}map, and a 200 with"error": true. The output shows the three replies to curl. - A client now needs three different checks for one idea, "not found". The order reply is the worst: status 200 tells every tool that the call worked.
A client, such as an Android app or a React page, reads error replies with code. In a real team the default shape is rarely the only one: one developer returns an empty 404, another returns {"msg": ...}, a third returns 200 with "error": true.
The client then needs special code for each endpoint, and a 200 for an error breaks every retry and logging tool. The rest of this module replaces all of this with one format: the RFC 9457 problem body that the ShopLite API contract uses for every 4xx and 5xx response.
Next step
Check your understanding
12 quick questions