Skip to main content

Bash Error Handling Patterns Library

Build a reusable Bash library of error handling patterns: trap handlers, retry logic, graceful degradation, and structured error reporting.

Fill in the placeholders

Edit the values, then copy your finished prompt.

Your Prompt
prompt.txt

                                

What this prompt does

This prompt creates a reusable Bash error-handling library (error_lib.sh) that any script in a [project_type] environment can source. It provides a set_strict_mode function with an option to treat unset variables as warnings for [compatibility_mode] scripts, a trap_handler capturing the failing command, line number, and call stack with [error_context] variables, a retry function with jitter to avoid a thundering herd among [parallel_workers], a subshell-based try/catch, a graceful_degradation function falling back via [fallback_strategy], a structured_error emitting JSON for [log_aggregator], and a test script.

The variables adapt the library to your stack. [error_context] defines which environment variables get attached to every error, [parallel_workers] informs the retry jitter so simultaneous retries don't synchronize, and [log_aggregator] shapes the JSON so it parses cleanly downstream. Centralizing these patterns means each script sources one tested library instead of reimplementing trap handlers and retries inconsistently.

When to use it

  • You write many deployment and ops scripts and want consistent error handling
  • Trap handlers that capture the failing line and call stack for fast root cause
  • Retry-with-jitter for flaky network calls across [parallel_workers]
  • Emitting structured JSON errors for ingestion by a log aggregator
  • A try/catch pattern in Bash via subshells with access to exit code and stderr
  • Graceful degradation that falls back through a defined [fallback_strategy]

Example output

You get an error_lib.sh exposing set_strict_mode, trap_handler, retry <max_attempts> <delay_seconds> <backoff_multiplier> <command>, a try/catch construct, graceful_degradation, and structured_error producing JSON with code, message, timestamp, and [error_context]. A companion test script exercises every function with passing and failing scenarios so you can verify the library before sourcing it elsewhere.

Pro tips

  • Source this one library everywhere rather than copy-pasting trap handlers; consistency is the whole point of [project_type] adopting it
  • Keep the retry's jitter enabled so [parallel_workers] retrying at once do not synchronize into a thundering herd against a recovering service
  • Populate [error_context] with the variables you actually grep for during incidents (environment, version, hostname) so errors are self-explaining
  • Shape structured_error JSON to match what [log_aggregator] expects, or the fields will not parse into searchable columns
  • Use [compatibility_mode] sparingly — treating unset variables as warnings weakens set -u, so reserve it for legacy scripts that need it
  • Run the included test script after any change to the library; an error-handling library that itself has a bug is dangerous everywhere it is sourced
  • Have trap_handler capture the line number and call stack, not just the exit code; knowing which command failed turns a vague non-zero exit into an actionable root cause
  • Wire graceful_degradation to a real [fallback_strategy] and log which path was taken, so a degraded response is visible in the logs rather than silently masking that the primary path failed

Frequently Asked Questions

Why add jitter to the retry logic?
Jitter randomizes the backoff delay so that `[parallel_workers]` failing at the same moment do not all retry in lockstep. Without it, synchronized retries create a thundering herd that can overwhelm a service just as it recovers, turning a brief blip into a sustained outage.
How does a try/catch work in Bash, which has no native one?
The library implements it using subshells: the try block runs in a subshell, and if it fails the catch block runs an error handler with access to the failed command's exit code and stderr. It is a pattern rather than a language feature, but it gives you structured error handling around risky commands.
What makes the structured errors useful?
The `structured_error` function outputs each error as a JSON object with code, message, timestamp, and `[error_context]` fields. When ingested by `[log_aggregator]`, these become searchable, filterable fields, so a 2am failure turns into a one-line query instead of grepping raw text across many scripts.
Can I use this with legacy scripts that rely on unset variables?
Yes. The `set_strict_mode` function offers an option to treat unset variables as warnings instead of errors for `[compatibility_mode]` scripts. Use it sparingly though, since it weakens the protection of set -u, and reserve it for legacy code that intentionally depends on unset variables.
Engr Mejba Ahmed

Need this built for real?

Engr Mejba Ahmed

AI Developer · Software Engineer

I'm Mejba — I design and ship production AI systems, automations, and full-stack apps. If you want this turned into a working solution for your team, let's talk.

More in Linux & Shell Scripting Prompts

Engr Mejba Ahmed

Engr Mejba Ahmed

Claude Code Expert · Online

👋

Hey there!

Quick Actions

WhatsApp Instant reply

Chat on WhatsApp

+880 1723 741224 · Instant reply

Popular Questions

Engr Mejba Ahmed is connected
Engr Mejba Ahmed is typing...
Engr Mejba Ahmed avatar

✉ Want me to follow up? Drop your email

Engr Mejba Ahmed avatar

📞 Connect Directly

Choose how you'd like to reach me

WhatsApp

+880 1723 741224

Email

[email protected]

✓ Details sent! I'll get back to you shortly.

Powered by OpenAI

335+

Blog Posts

25

AI Courses

63

Projects

Services & Expertise

Pricing & Process

Learning & Resources

Connect & Support