If you don't handle an error and an exception gets thrown at runtime in a Spring Boot application, the client will typically see a 5xx HTTP error. Specifically, a 500 Internal Server Error is the most common response when an unhandled exception occurs.
HTTP 4xx vs. 5xx Errors:
- 4xx Errors (Client-Side Errors): These indicate that the client made a bad request or there was an issue with the request itself. Examples include:
- 400 Bad Request: Invalid request sent by the client.
- 404 Not Found: Resource not found.
- 5xx Errors (Server-Side Errors): These indicate that something went wrong on the server while processing the request. The most common error in this category is:
- 500 Internal Server Error: A general error indicating that the server failed to handle the request.
Why the Client Sees a 5xx Error
- 5xx errors represent server-side errors, which means something went wrong on the server while processing the request.
- If you don’t handle an exception explicitly in your code, Spring will classify this as an internal error, resulting in a 500 HTTP response code.
Who Converts the Exception into an HTTP Error?
When an exception is not explicitly handled by your application code, Spring's built-in exception handling mechanism (specifically, the DefaultHandlerExceptionResolver
) takes over. It catches the unhandled exception and converts it into a suitable HTTP response.
❓ How It Works in Spring
- Exception Occurs: A runtime exception is thrown in a controller or service method.
- Spring’s Exception Handling Kicks In: If you haven't defined a specific handler for the exception (like with
@ExceptionHandler
or@ControllerAdvice
), Spring will use its default mechanisms to catch it. - HTTP 500 Response: The client receives a 500 Internal Server Error, indicating that the server encountered an unexpected condition.
Handling Errors Gracefully
To prevent this default behavior and provide more meaningful responses, you can:
- Use @ExceptionHandler
to handle specific exceptions and return custom error messages.
- Use @ControllerAdvice
to handle exceptions globally across all controllers.
Example:
@ControllerAdvice public class GlobalExceptionHandler {
@ExceptionHandler(ArithmeticException.class)
public ResponseEntity<String> handleArithmeticException(ArithmeticException ex) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid arithmetic operation");
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleGenericException(Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An unexpected error occurred");
}
}