Fix Improper Error Handling in Spring Boot
Default Spring Boot error handling is a goldmine for reconnaissance. Out-of-the-box configuration often leaks stack traces, package structures, and dependency versions through the Whitelabel Error Page. As an AppSec pro, your goal is to zero-out information leakage by intercepting all exceptions and returning sanitized, opaque responses.
The Vulnerable Pattern
@RestController
public class UserController {
@GetMapping("/user/{id}")
public User getUser(@PathVariable String id) {
// If id is not found, this throws a RuntimeException
// Spring's default behavior will return a 500 with a full stack trace if configured poorly
return userService.findById(id).orElseThrow(() -> new RuntimeException("Database connection failed at 10.0.0.5:5432"));
}
}
The Secure Implementation
The vulnerability lies in exposing internal system state via exception messages and stack traces. The fix implements a `@RestControllerAdvice` which acts as an interceptor for all thrown exceptions. This ensures that even if a developer throws a raw exception, the client only receives a generic 'An internal server error occurred' message. Additionally, hard-coding `server.error.include-stacktrace=never` in your properties file acts as a fail-safe against default Spring behavior that might trigger during startup or filter-level crashes.
@RestControllerAdvice public class GlobalExceptionHandler {@ExceptionHandler(Exception.class) public ResponseEntity<Map<String, String>> handleAllExceptions(Exception ex) { // Log the actual error internally for debugging // logger.error("Internal Error: ", ex); Map<String, String> errorBody = new HashMap<>(); errorBody.put("status", "error"); errorBody.put("message", "An internal server error occurred"); return new ResponseEntity<>(errorBody, HttpStatus.INTERNAL_SERVER_ERROR); }}
// application.properties server.error.include-stacktrace=never server.error.include-message=never server.error.include-exception=false
Your Spring Boot API
might be exposed to Improper Error Handling
74% of Spring Boot apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.