From 10b980fb86c12fb1237fa7759bc444e18d2fd72f Mon Sep 17 00:00:00 2001 From: CanbiZ <47820557+MickLesk@users.noreply.github.com> Date: Tue, 20 May 2025 08:52:48 +0200 Subject: [PATCH] trap handler --- misc/core.func | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/misc/core.func b/misc/core.func index fb5937c..5cb594e 100644 --- a/misc/core.func +++ b/misc/core.func @@ -30,6 +30,7 @@ _CORE_FUNC_LOADED=1 load_functions() { [[ -n "${__FUNCTIONS_LOADED:-}" ]] && return __FUNCTIONS_LOADED=1 + setup_trap_abort_handling color formatting icons @@ -39,6 +40,67 @@ load_functions() { # add more } +setup_trap_abort_handling() { + trap '__handle_signal_abort SIGINT' SIGINT + trap '__handle_signal_abort SIGTERM' SIGTERM + trap '__handle_unexpected_error $?' ERR +} + +__handle_signal_abort() { + local signal="$1" + echo + [ -n "${SPINNER_PID:-}" ] && kill "$SPINNER_PID" 2>/dev/null && wait "$SPINNER_PID" 2>/dev/null + + case "$signal" in + SIGINT) + msg_error "Script aborted by user (CTRL+C)" + exit 130 + ;; + SIGTERM) + msg_error "Script terminated (SIGTERM)" + exit 143 + ;; + *) + msg_error "Script interrupted (unknown signal: $signal)" + exit 1 + ;; + esac +} + +__handle_unexpected_error() { + local exit_code="$1" + echo + [ -n "${SPINNER_PID:-}" ] && kill "$SPINNER_PID" 2>/dev/null && wait "$SPINNER_PID" 2>/dev/null + + case "$exit_code" in + 1) + msg_error "Generic error occurred (exit code 1)" + ;; + 2) + msg_error "Misuse of shell builtins (exit code 2)" + ;; + 126) + msg_error "Command invoked cannot execute (exit code 126)" + ;; + 127) + msg_error "Command not found (exit code 127)" + ;; + 128) + msg_error "Invalid exit argument (exit code 128)" + ;; + 130) + msg_error "Script aborted by user (CTRL+C)" + ;; + 143) + msg_error "Script terminated by SIGTERM" + ;; + *) + msg_error "Unexpected error occurred (exit code $exit_code)" + ;; + esac + exit "$exit_code" +} + # ------------------------------------------------------------------------------ # Sets ANSI color codes used for styled terminal output. # ------------------------------------------------------------------------------