GuardAPI Logo
GuardAPI
Automated Security Protocol

How to fix Improper Error Handling
in Plug

Executive Summary

Plug is the core abstraction for Elixir web servers. By default, unhandled exceptions can bubble up and expose sensitive stack traces, module names, and internal state to the end user. In production, this verbosity provides an attacker with a roadmap of your application logic and dependency tree. Securing Plug requires implementing a centralized error handler that sanitizes client-facing responses while maintaining internal observability.

The Vulnerable Pattern

VULNERABLE CODE
defmodule MyApp.Router do
  use Plug.Router
  plug :match
  plug :dispatch

get “/debug_crash” do # This crash will leak a full Erlang/Elixir stack trace to the browser # if the adapter is configured to show errors. Map.fetch!(%{}, :missing_key) send_resp(conn, 200, “OK”) end end

The Secure Implementation

The fix utilizes 'Plug.ErrorHandler' to intercept any exceptions thrown during the plug pipeline execution. By overriding 'handle_errors/2', we separate the internal failure details (logged via Logger) from the external response. This prevents Information Exposure (CWE-209). Ensure that in your Phoenix or Plug application configuration ('config/prod.exs'), 'debug_errors' is set to 'false' to prevent the default debug wrapper from hijacking the response.

SECURE CODE
defmodule MyApp.Router do
  use Plug.Router
  use Plug.ErrorHandler
  require Logger

plug :match plug :dispatch

get “/debug_crash” do Map.fetch!(%{}, :missing_key) send_resp(conn, 200, “OK”) end

@impl Plug.ErrorHandler def handle_errors(conn, %{kind: _kind, reason: reason, stack: stack}) do # Log the real error for internal debugging Logger.error(Exception.format(:error, reason, stack))

# Return a generic response to the user
send_resp(conn, conn.status, "Internal Server Error")

end end

System Alert • ID: 6429
Target: Plug API
Potential Vulnerability

Your Plug API might be exposed to Improper Error Handling

74% of Plug 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.