Fix Improper Error Handling in Micronaut
Leaking stack traces is a gift to attackers. In Micronaut, default error behavior or lazy catch blocks can expose internal package structures, library versions, and database schemas. To secure the app, you must intercept exceptions and return sanitized, structured responses that provide zero reconnaissance data to an external actor.
The Vulnerable Pattern
@Controller("/users")
public class UserController {
@Get("/{id}")
public HttpResponse getUser(String id) {
try {
// Business logic that might fail
throw new SQLException("Connection refused to 10.0.5.21:5432");
} catch (Exception e) {
// VULNERABLE: Directly returning the exception object or its message
// leaks internal infrastructure details and stack traces to the client.
return HttpResponse.serverError(e);
}
}
}
The Secure Implementation
The secure implementation utilizes Micronaut's ExceptionHandler interface to create a global catch-all for unhandled throwables. Instead of allowing the framework to serialize the exception stack trace to the HTTP body, we intercept it, log the sensitive details to a secure internal log file, and return a generic JSON error message. The 'ref_id' (UUID) allows developers to correlate the user's error report with the server-side logs without revealing any architectural secrets to the attacker.
@Produces @Singleton @Requires(classes = {Throwable.class, ExceptionHandler.class}) public class GlobalExceptionHandler implements ExceptionHandler> { private static final Logger LOG = LoggerFactory.getLogger(GlobalExceptionHandler.class); @Override public HttpResponse<?> handle(HttpRequest request, Throwable exception) { String errorId = java.util.UUID.randomUUID().toString(); // Log the full stack trace internally for debugging LOG.error("Unhandled Exception [ID: {}]: {}", errorId, exception.getMessage(), exception); // Return a sanitized response to the client return HttpResponse.serverError(Map.of( "status", "error", "message", "An internal error occurred. Contact support with the reference ID.", "ref_id", errorId )); }
}
Your Micronaut API
might be exposed to Improper Error Handling
74% of Micronaut 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.