Skip to content

Instantly share code, notes, and snippets.

@fayak
Last active August 8, 2024 16:29
Show Gist options
  • Save fayak/866e37739ad11ee43c2f34495b2358f3 to your computer and use it in GitHub Desktop.
Save fayak/866e37739ad11ee43c2f34495b2358f3 to your computer and use it in GitHub Desktop.
Error handling in bash with sentry support
#!/usr/bin/env bash
set -eTEuo pipefail
function get_pgid() {
cut -d " " -f 5 < "/proc/$$/stat" | tr ' ' '\n'
}
pgid="$(get_pgid)"
if [[ "$$" != "$pgid" ]]; then
exec setsid "$(readlink -f "$0")" "$@"
fi
SCRIPT_DIR="$( cd -- "$( dirname -- "${BASH_SOURCE[0]:-.}" )" &> /dev/null && pwd )"
function stacktrace() {
cd "$SCRIPT_DIR"
local i=1 line file func
while read -r line func file < <(caller "$i"); do
echo "[$i] $file:$line $func(): $(sed -n "$line"p "$file")" 1>&2
i=$((i+1))
done
}
trap 'set +x; end 1' SIGUSR1 SIGTERM
trap 'set +x; end' EXIT
trap 'set +x; catch_err $?' ERR
function catch_err() {
stacktrace_msg="$(stacktrace 2>&1)"
send_sentry "$1" "$stacktrace_msg"
1>&2 echo -e "$stacktrace_msg"
if [[ "$$" == "$BASHPID" ]]; then
end 1
else
PGID="$(get_pgid)"
kill -10 -- "$PGID"
sleep 1
kill -15 -- -"$PGID"
fi
}
function cleanup() {
rm -rf "${TMP_FILE:-}" || true # FIXME
}
function end() {
local return_code="${1:-}"
trap '' EXIT
set +e # At this point, if things fail, we can't do much more
[[ -z "$(jobs -p)" ]] || kill "$(jobs -p)" 2> /dev/null
if [[ "$$" == "$BASHPID" ]]; then
cleanup
fi
[[ -z "$return_code" ]] || exit "$return_code"
}
function send_sentry() {
# Don't do anything if sentry-cli command doesn't exist
if ! command -v sentry-cli &> /dev/null; then
return
fi
local return_code="$1"
local stacktrace_msg="$2"
cd "$SCRIPT_DIR"
local line file func
read -r line func file < <(caller 1)
error_line="$(sed -n "$line"p "$file" | awk '{$1=$1};1')"
sentry-cli send-event -m "$error_line: return code $return_code" \
-a "$stacktrace_msg" \
-t user_sudo:"${SUDO_USER:-${USER:-undefined}}" || echo Could not send sentry event 1>&2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment