Spring Boot Default and Custom Error Handling

Niraj Kumar
3 min readDec 16, 2024

--

The default error-handling mechanism in Spring Boot is designed to provide a standard response for unhandled exceptions in web applications, including REST APIs and web-based user interfaces. Here’s an overview of how Spring Boot handles errors by default:

1. Default Error Handling in Spring Boot

When an unhandled exception occurs in a Spring Boot application, the framework uses its default error-handling mechanism, which relies on:

Error Controller:

  • The built-in BasicErrorController handles error responses.
  • This controller processes errors and returns an appropriate response, either in JSON (for REST APIs) or as an HTML error page (for web applications).

Error Attributes:

  • The DefaultErrorAttributes class collects error details and makes them available for rendering in the response.

Error Pages:

  • By default, Spring Boot serves an HTML error page if the client accepts text/html.
  • For REST APIs, a JSON response is returned if the client accepts application/json.

2. Default JSON Error Response

For REST APIs, the default error response typically includes the following fields:

{
"timestamp": "2024-12-15T12:34:56.789",
"status": 500,
"error": "Internal Server Error",
"message": "NullPointerException",
"path": "/api/resource"
}

Fields Explained:

  • timestamp: When the error occurred.
  • status: HTTP status code (e.g., 404 for Not Found, 500 for Internal Server Error).
  • error: A brief error description.
  • message: The exception’s message (if available).
  • path: The URL path where the error occurred.

3. Customizing Default Error Handling

Spring Boot allows easy customization of its default error-handling behavior. Below are some common methods for customization:

a. Custom Error Messages

You can configure error messages for specific HTTP status codes by adding error pages in src/main/resources/templates/error/.

Example:

  • Add an error.html file for general errors.
  • Add error-404.html for 404 errors or error-500.html for 500 errors.
<!-- src/main/resources/templates/error.html -->
<!DOCTYPE html>
<html>
<head>
<title>Error</title>
</head>
<body>
<h1>Something went wrong!</h1>
</body>
</html>

b. Customize Error Attributes

You can extend the DefaultErrorAttributes class to modify the default JSON error response.

Example:

@Component
public class CustomErrorAttributes extends DefaultErrorAttributes {

@Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) {
Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest, options);
errorAttributes.put("customMessage", "Custom error message");
return errorAttributes;
}
}

c. Use @ControllerAdvice for Global Exception Handling

Define a global exception handler using @ControllerAdvice and @ExceptionHandler.

Example:

@RestControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(Exception.class)
public ResponseEntity<Map<String, Object>> handleException(Exception ex, WebRequest request) {
Map<String, Object> response = new HashMap<>();
response.put("timestamp", LocalDateTime.now());
response.put("message", ex.getMessage());
response.put("details", request.getDescription(false));
return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
}

d. Override the Error Controller

You can replace the default BasicErrorController with a custom implementation.

Example:

@RestController
@RequestMapping("/error")
public class CustomErrorController implements ErrorController {

@GetMapping
public ResponseEntity<Map<String, Object>> handleError(HttpServletRequest request) {
Map<String, Object> response = new HashMap<>();
response.put("status", request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE));
response.put("message", "Custom error response");
return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
}

4. HTTP Status Codes

Spring Boot automatically maps exceptions to appropriate HTTP status codes:

  • 404 (Not Found): No matching handler or endpoint.
  • 400 (Bad Request): Invalid request data or parameters.
  • 500 (Internal Server Error): Unhandled exceptions.

5. Configuration Properties for Error Handling

Spring Boot provides several configuration options in application.properties to control error handling:

PropertyDescriptionserver.error.pathSet the custom path for the error page (default: /error).server.error.include-stacktraceInclude stack trace in error response (never, on_trace_param, always).server.error.include-messageInclude exception message in the response (never, on_param, always).server.error.whitelabel.enabledEnable/disable the default Whitelabel Error Page (true by default).

Example:

server.error.path=/custom-error
server.error.include-stacktrace=never
server.error.include-message=always

6. Advanced Exception Handling

For more advanced use cases:

  • Use ResponseEntityExceptionHandler to handle Spring MVC exceptions like MethodArgumentNotValidException.

Example:

@ControllerAdvice
public class CustomRestExceptionHandler extends ResponseEntityExceptionHandler {

@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatus status,
WebRequest request) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getFieldErrors().forEach(error ->
errors.put(error.getField(), error.getDefaultMessage())
);
return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
}
}

Summary

  • Spring Boot’s default error-handling mechanism provides structured responses for unhandled exceptions.
  • It can be customized at various levels, from modifying error attributes to implementing global exception handlers.
  • For REST APIs, the default mechanism outputs helpful JSON responses, while for web applications, HTML error pages are displayed.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Niraj Kumar
Niraj Kumar

Written by Niraj Kumar

Architect | Lead Developer | Cloud Computing | Microservices | Java | React | Angular | Kafka | AI/ML

No responses yet

Write a response