Exception Handling in Spring Boot MVC vs REST | BasicErrorController
Building resilient software involves managing errors effectively. Exception handling is pivotal to providing a seamless user experience and making debugging easier for developers. However, when working with Spring Boot, the exception handling mechanism differs significantly between MVC applications and REST APIs. MVC applications often return rendered HTML error pages, whereas REST APIs typically respond with JSON-formatted messages.
This guide explores the differences in how Spring Boot handles exceptions in MVC applications versus REST APIs. We’ll examine error rendering, the role of BasicErrorController
, distinctions between HTML error pages and JSON responses, and how to customize ErrorAttributes
for tailored error handling.
Table of Contents
- Key Differences in Error Rendering (HTML vs JSON)
- The Role of BasicErrorController in MVC
- Error Pages (error.html) vs API Responses
- Customizing ErrorAttributes
- Summary
Key Differences in Error Rendering (HTML vs JSON)
One of the key distinctions between Spring Boot MVC and REST lies in how errors are presented to clients.
Error Rendering in MVC Applications
Spring MVC aims to provide a rich, user-friendly experience for handling exceptions by serving dynamically rendered HTML error pages.
For example:
- When an unhandled exception occurs or a
404 Not Found
status is returned, the user is presented with an error page. - This is ideal for traditional web applications where users interact via a browser.
By default, Spring Boot generates a plain HTML error page with basic information like the error message, HTTP status, and a timestamp.
Error Rendering in REST APIs
For REST APIs, the focus shifts to machine-readable error messages, usually in JSON format. RESTful APIs cater to systems communicating over HTTP, so errors must be concise and structured.
The default response for an exception in a REST API typically looks like this:
{
"timestamp": "2025-06-12T16:30:00",
"status": 404,
"error": "Not Found",
"message": "Resource not found",
"path": "/api/resource/123"
}
Comparison of HTML vs JSON Rendering
Aspect | MVC (HTML) | REST (JSON) |
---|---|---|
Target Audience | End-users (browser users). | Developers/Consumers (API clients). |
Response Format | Rendered HTML error pages. | JSON-formatted error messages. |
Use Case | Traditional web applications. | APIs for system-to-system communication. |
These differences highlight the need for customizing error mechanisms depending on your application type.
The Role of BasicErrorController in MVC
Error handling in Spring Boot relies on well-defined conventions, and the BasicErrorController
plays a significant role in this process.
What is BasicErrorController?
The BasicErrorController
is Spring Boot’s default controller for handling errors. It provides a generic implementation to handle:
- HTTP errors (e.g.,
404
,500
). - Unhandled exceptions in the application.
How It Works
When an exception occurs, Spring Boot redirects the request to /error
, which is mapped to the BasicErrorController
. The controller then generates an error response based on the request type.
- For browsers (text/html requests),
BasicErrorController
renders an HTML error page. - For REST clients (application/json requests), it produces a JSON error response.
Customization with application.properties
You can configure the behavior of the BasicErrorController
using the following properties:
server.error.include-message=always
server.error.path=/custom-error
include-message
determines whether error messages are included in the response.path
lets you override the default/error
endpoint.
Example in Action
Consider a simple REST controller:
@RestController
@RequestMapping("/api/resources")
public class ResourceController {
@GetMapping("/{id}")
public ResponseEntity<String> getResource(@PathVariable int id) {
if (id > 1000) {
throw new RuntimeException("Invalid resource ID");
}
return ResponseEntity.ok("Resource found");
}
}
For browsers accessing /api/resources/2000
, the default BasicErrorController
generates an HTML error page. For JSON clients, it sends an HTTP 500 error along with a JSON error response.
This default behavior works out-of-the-box but can be customized further, as we’ll explore later.
Error Pages (error.html) vs API Responses
Error Pages in MVC
For traditional MVC applications, you can define custom error pages to provide a polished user experience.
Defining a Custom Error Page
Spring Boot allows you to create an error.html
file under the src/main/resources/templates
directory to override the default error page.
Example: error.html
:
<!DOCTYPE html>
<html>
<head>
<title>Error</title>
</head>
<body>
<h1>Something went wrong</h1>
<p>Status Code: [[${status}]]</p>
<p>Message: [[${error}]]</p>
</body>
</html>
This file will render whenever an error occurs in the browser.
Configuring Error Pages for Different Status Codes
You can also define error pages for specific status codes:
server.error.whitelabel.enabled=false
server.error.include-binding-errors=always
API Responses for REST
For REST APIs, Spring Boot provides JSON error responses by default. These responses are typically generated by ErrorAttributes
.
Example API Error Response
For a REST endpoint, the default error might look like:
{
"timestamp": "2025-06-12T16:35:45",
"status": 404,
"error": "Not Found",
"message": "Resource not found",
"path": "/api/resources/1234"
}
Unlike HTML error pages, these responses are structured, easy to parse, and include details like:
timestamp
– When the error occurred.status
– The HTTP status code.path
– The endpoint that caused the error.
REST APIs prioritize clarity and machine-readability in error handling, making JSON the preferred format.
Customizing ErrorAttributes
What are ErrorAttributes?
ErrorAttributes
is an interface used by Spring Boot to generate error details for both HTML error pages and API responses. It determines the contents of the error object returned via BasicErrorController
.
Implementing Custom ErrorAttributes
To customize your API error responses, you can override the default error attributes by creating a custom implementation.
Example:
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> errorAttributes = super.getErrorAttributes(webRequest, options.withDefaults());
errorAttributes.put("customMessage", "This is a custom error message");
return errorAttributes;
}
}
By doing this:
- You can add extra fields to the error response, such as
customMessage
. - Customize fields like
message
orerror
to tailor them for your use case.
Changing Error Structure
With custom ErrorAttributes
, you can generate a completely custom structure for API responses:
{
"timestamp": "2025-06-12T16:40:00",
"status": 500,
"error": "Server Error",
"message": "Unexpected error occurred",
"customMessage": "Contact support for help"
}
This level of customization makes APIs more intuitive and informative for clients.
Summary
Exception handling in Spring Boot varies significantly between MVC and REST applications. Understanding these differences ensures that developers can provide appropriate responses tailored to user needs.
Key Takeaways:
- Error Rendering:
- MVC applications rely on HTML error pages, while REST APIs return machine-readable JSON responses.
- BasicErrorController:
- This default controller handles errors for both browsers and APIs, providing a consistent fallback mechanism.
- Custom Pages:
- MVC applications can use
error.html
for polished error rendering, while REST APIs lean on structured JSON responses.
- MVC applications can use
- Customizing ErrorAttributes:
- For tailored responses, overriding
ErrorAttributes
enables fine-grained control over error contents.
- For tailored responses, overriding
By leveraging these techniques, you can build user-friendly MVC applications and developer-centric REST APIs with robust exception handling. Adopt these practices to improve diagnostics, enhance usability, and deliver high-quality applications!