#!/usr/bin/env bash # Error handling functions # Usage: source "$SCRIPT_DIR/lib/common/error-handling.sh" # Source logging if not already sourced [ -z "$(type -t log_error)" ] && source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/logging.sh" # Error exit function error_exit() { local message="$1" local exit_code="${2:-1}" log_error "$message" exit "$exit_code" } # Cleanup function registry declare -a CLEANUP_FUNCTIONS=() # Register cleanup function register_cleanup() { local func="$1" CLEANUP_FUNCTIONS+=("$func") } # Execute cleanup functions cleanup_on_exit() { local exit_code=$? for func in "${CLEANUP_FUNCTIONS[@]}"; do if type -t "$func" >/dev/null; then "$func" || true fi done exit $exit_code } # Setup error traps setup_error_traps() { # Trap ERR - command failures trap 'error_exit "Line $LINENO: Command failed: $BASH_COMMAND" $?' ERR # Trap EXIT - cleanup trap 'cleanup_on_exit' EXIT # Trap INT - Ctrl+C trap 'log_warn "Interrupted by user"; exit 130' INT # Trap TERM - termination trap 'log_warn "Terminated"; exit 143' TERM } # Check if error handling is enabled is_error_handling_enabled() { [[ $- == *e* ]] }