#!/usr/bin/env bash # Error handling functions # Usage: source "$(dirname "$0")/error-handling.sh" # Requires: logging.sh # Set error trap set_error_trap() { trap 'error_handler $? $LINENO' ERR } # Error handler error_handler() { local exit_code=$1 local line_number=$2 log_error "Error occurred at line $line_number with exit code $exit_code" # Call cleanup function if defined if [ "$(type -t cleanup)" = "function" ]; then cleanup fi exit "$exit_code" } # Cleanup function template (can be overridden) cleanup() { log_debug "Running cleanup..." # Override this function in scripts that need cleanup } # Exit with error message exit_with_error() { local message="$1" local exit_code="${2:-1}" log_error "$message" exit "$exit_code" } # Exit with success message exit_with_success() { local message="$1" log_success "$message" exit 0 }