Fix Improper Error Handling in Slim
Improper error handling in Slim frameworks is a classic Information Disclosure vector. By default, verbose error middleware leaks stack traces, environment paths, and potentially database credentials to the end-user. To secure a Slim application, you must decouple error reporting for developers from the error responses sent to clients.
The Vulnerable Pattern
$app = AppFactory::create();
// SEVERE RISK: displayErrorDetails is true in production // This leaks full stack traces and sensitive context to the browser $app->addErrorMiddleware(true, true, true);
$app->get(‘/api/data’, function ($request, $response) { throw new \Exception(‘Query failed: SELECT * FROM users WHERE secret=“password123”’); });
$app->run();
The Secure Implementation
The fix implements environment-aware configuration. By setting `displayErrorDetails` to `false` in production, Slim's default error handler suppresses the stack trace. The addition of a custom Error Renderer ensures that even when an unhandled exception occurs, the client receives a generic, sanitized JSON response instead of a raw PHP dump. Always use a dedicated logger (like Monolog) in conjunction with `addErrorMiddleware(..., true, ...)` to ensure visibility for debugging without exposing the attack surface.
$app = AppFactory::create();
// 1. Detect environment $isProduction = getenv(‘APP_ENV’) === ‘production’;
// 2. Suppress details in production, but keep logging enabled $errorMiddleware = $app->addErrorMiddleware(!$isProduction, true, true);
// 3. Custom Error Handler to return sanitized JSON $errorHandler = $errorMiddleware->getDefaultErrorHandler(); $errorHandler->registerErrorRenderer(‘application/json’, function (Throwable $exception, bool $displayErrorDetails) { $payload = [‘error’ => ‘Internal Server Error’]; if ($displayErrorDetails) { $payload[‘message’] = $exception->getMessage(); $payload[‘trace’] = $exception->getTrace(); } return json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT); });
$app->run();
Your Slim API
might be exposed to Improper Error Handling
74% of Slim 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.