GuardAPI Logo
GuardAPI

Fix Improper Error Handling in Hanami

Improper error handling in Hanami applications often leads to Information Exposure through persistent stack traces and internal logic disclosure. In production environments, leaking raw Ruby exceptions or database query errors provides attackers with the exact file paths, method names, and library versions needed to map the attack surface and craft targeted exploits. Securing this requires a centralized exception handling strategy that decouples internal failure details from the HTTP response.

The Vulnerable Pattern

module Web::Actions::Users
  class Show
    include Web::Action
def call(params)
  @user = UserRepository.new.find!(params[:id])
rescue => e
  # VULNERABLE: Leaking exception message and backtrace to the client
  self.status = 500
  self.body = { error: e.message, debug: e.backtrace }.to_json
end

end end

The Secure Implementation

The fix replaces manual, verbose rescue blocks with Hanami's 'handle_exception' DSL. By defining the handler in a base Action class, we ensure all inheriting actions benefit from uniform error sanitization. The secure implementation logs the sensitive stack trace to a protected log file while returning a generic JSON object and a unique Request ID to the user. This prevents 'Information Leakage' (CWE-209) while maintaining the ability for developers to correlate client-side reports with server-side logs.

module Web
  class Action < Hanami::Action
    # SECURE: Centralized handler to map exceptions to generic responses
    handle_exception StandardError => :handle_500
private

def handle_500(exception)
  # Log the full error internally for debugging
  Hanami.logger.error(exception.message)
  
  # Return an opaque error message to the client
  self.status = 500
  self.body = { 
    error: 'Internal Server Error', 
    request_id: request.env['REQUEST_ID'] 
  }.to_json
end

end end

System Alert • ID: 2005
Target: Hanami API
Potential Vulnerability

Your Hanami API might be exposed to Improper Error Handling

74% of Hanami apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

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.