Standardize error handling with cleanup trap
- Add cleanup function called on EXIT trap - Add ERRORS_OCCURRED and WARNINGS_OCCURRED counters - Make handle_error support non-fatal errors with optional parameter - Add proper exit codes for INT (130) and TERM (143) signals - Add summary of errors/warnings at the end of diagnostics - Redirect error messages to stderr #10 Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
51
proxDoc.sh
51
proxDoc.sh
@@ -48,18 +48,42 @@ print_header() {
|
||||
}
|
||||
|
||||
|
||||
# Error handling flags
|
||||
ERRORS_OCCURRED=0
|
||||
WARNINGS_OCCURRED=0
|
||||
|
||||
cleanup() {
|
||||
# Cleanup function called on exit
|
||||
local exit_code=$?
|
||||
if [[ $exit_code -ne 0 ]]; then
|
||||
echo -e "\n${RED}Script terminated with exit code: $exit_code${NC}"
|
||||
fi
|
||||
# Add any cleanup tasks here (temp files, etc.)
|
||||
}
|
||||
|
||||
handle_error() {
|
||||
echo -e "${RED}Error: $1${NC}"
|
||||
exit 1
|
||||
local message="$1"
|
||||
local fatal="${2:-true}" # Default to fatal error
|
||||
echo -e "${RED}Error: $message${NC}" >&2
|
||||
ERRORS_OCCURRED=$((ERRORS_OCCURRED + 1))
|
||||
if [[ "$fatal" == "true" ]]; then
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
log_message() {
|
||||
local level=$1
|
||||
local message=$2
|
||||
case $level in
|
||||
local level="$1"
|
||||
local message="$2"
|
||||
case "$level" in
|
||||
info) echo -e "${GREEN}[INFO]${NC} $message" ;;
|
||||
warn) echo -e "${YELLOW}[WARN]${NC} $message" ;;
|
||||
error) echo -e "${RED}[ERROR]${NC} $message" ;;
|
||||
warn)
|
||||
echo -e "${YELLOW}[WARN]${NC} $message"
|
||||
WARNINGS_OCCURRED=$((WARNINGS_OCCURRED + 1))
|
||||
;;
|
||||
error)
|
||||
echo -e "${RED}[ERROR]${NC} $message" >&2
|
||||
ERRORS_OCCURRED=$((ERRORS_OCCURRED + 1))
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
@@ -747,6 +771,13 @@ runDiags() {
|
||||
|
||||
echo ""
|
||||
log_message info "Examination complete"
|
||||
|
||||
# Print summary if there were issues
|
||||
if [[ $WARNINGS_OCCURRED -gt 0 || $ERRORS_OCCURRED -gt 0 ]]; then
|
||||
echo -e "\n${YELLOW}=== Summary ===${NC}"
|
||||
[[ $WARNINGS_OCCURRED -gt 0 ]] && echo -e "Warnings: $WARNINGS_OCCURRED"
|
||||
[[ $ERRORS_OCCURRED -gt 0 ]] && echo -e "Errors: $ERRORS_OCCURRED"
|
||||
fi
|
||||
}
|
||||
|
||||
# Whitelist of valid command options
|
||||
@@ -812,8 +843,10 @@ if [[ $EUID -ne 0 ]]; then
|
||||
handle_error "This script must be run as root"
|
||||
fi
|
||||
|
||||
# Set trap for interrupts
|
||||
trap 'echo -e "${RED}Script interrupted.${NC}"; exit 1' INT TERM
|
||||
# Set trap for cleanup and interrupts
|
||||
trap cleanup EXIT
|
||||
trap 'echo -e "\n${RED}Script interrupted by user.${NC}"; exit 130' INT
|
||||
trap 'echo -e "\n${RED}Script terminated.${NC}"; exit 143' TERM
|
||||
|
||||
if [[ -n $argOne ]]; then
|
||||
checkForInput "$argOne"
|
||||
|
||||
Reference in New Issue
Block a user