Fix Improper Error Handling in AdonisJS
Improper error handling in AdonisJS is a goldmine for reconnaissance. Default behavior or poorly configured handlers often leak stack traces, database schema details, and file paths via the response body. This technical debt allows attackers to map the application's internal structure and identify specific library versions for exploit targeting. A hardened AdonisJS application must implement a centralized Exception Handler that sanitizes production output while maintaining internal logging visibility.
The Vulnerable Pattern
// app/Exceptions/Handler.ts import HttpExceptionHandler from '@ioc:Adonis/Core/HttpExceptionHandler'
export default class ExceptionHandler extends HttpExceptionHandler { public async handle(error, ctx) { // VULNERABILITY: Directly returning the error object to the client // This leaks stack traces, environment details, and SQL queries return ctx.response.status(error.status || 500).send({ status: ‘error’, message: error.message, stack: error.stack, code: error.code }) } }
The Secure Implementation
The fix leverages the AdonisJS centralized ExceptionHandler to intercept all failures. By checking the NODE_ENV, we ensure that sensitive data like 'error.stack' or raw 'E_ROW_NOT_FOUND' messages never reach the public web. The secure implementation logs the full trace to the server-side logs (for debugging) but returns a generic, non-descriptive JSON object to the client. This prevents 'Error-Based Enumeration' and hides the underlying tech stack from automated scanners.
// app/Exceptions/Handler.ts import Logger from '@ioc:Adonis/Core/Logger' import HttpExceptionHandler from '@ioc:Adonis/Core/HttpExceptionHandler' import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'export default class ExceptionHandler extends HttpExceptionHandler { constructor() { super(Logger) }
public async handle(error: any, ctx: HttpContextContract) { // 1. Internal Logging: Capture the ‘gore’ for the dev team Logger.error(
${error.status || 500} - ${error.message}: ${error.stack})// 2. Client Sanitization: Mask details in production if (process.env.NODE_ENV === 'production') { const status = error.status || 500 const message = status === 404 ? 'Resource not found' : 'An internal server error occurred' return ctx.response.status(status).send({ errors: [{ message }] }) } // 3. Verbose output only for development return super.handle(error, ctx)
} }
Protect your AdonisJS API
Don't rely on manual checks. GuardAPI's Gemini 3 Pro engine detects Improper Error Handling and logic flaws in seconds.
Run Automated AuditVerified 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.