|
4 | 4 | # @description Core functions for any Bash program
|
5 | 5 |
|
6 | 6 | # @description Adds a handler for a particular `trap` signal or event. Noticably,
|
7 |
| -# unlike the 'builtin' trap, this does not override any other existing handlers |
| 7 | +# unlike the 'builtin' trap, this does not override any other existing handlers. The first argument |
| 8 | +# to the handler is the exit code of the last command that ran before the particular 'trap' |
8 | 9 | # @arg $1 string Function to execute on an event. Integers are forbiden
|
9 | 10 | # @arg $2 string Event signal
|
10 | 11 | # @example
|
@@ -48,9 +49,16 @@ core.trap_add() {
|
48 | 49 | printf -v global_trap_handler_name '%q' "core.private.trap_handler_${signal_spec}"
|
49 | 50 |
|
50 | 51 | if ! eval "$global_trap_handler_name() {
|
51 |
| - core.private.util.trap_handler_common '$signal_spec' |
| 52 | + local ___exit_code_original=\$? |
| 53 | + if core.private.util.trap_handler_common '$signal_spec' \"\$___exit_code_original\"; then |
| 54 | + return \$___exit_code_original |
| 55 | + else |
| 56 | + local ___exit_code_user=\$? |
| 57 | + core.print_error_fn \"User-provided trap handler spectacularly failed with exit code \$___exit_code_user\" |
| 58 | + return \$___exit_code_user |
| 59 | + fi |
52 | 60 | }"; then
|
53 |
| - core.panic 'Could not eval function' |
| 61 | + core.panic 'Failed to eval function' |
54 | 62 | fi
|
55 | 63 | # shellcheck disable=SC2064
|
56 | 64 | trap "$global_trap_handler_name" "$signal_spec"
|
@@ -265,9 +273,11 @@ core.panic() {
|
265 | 273 | # @noargs
|
266 | 274 | # @example
|
267 | 275 | # err_handler() {
|
268 |
| -# local exit_code=$? |
| 276 | +# local exit_code=$1 # Note that this isn't `$?` |
269 | 277 | # core.print_stacktrace
|
270 |
| -# exit $exit_code |
| 278 | +# |
| 279 | +# # Note that we're not doing `exit $exit_code` because |
| 280 | +# # that is handled automatically |
271 | 281 | # }
|
272 | 282 | # core.trap_add 'err_handler' ERR
|
273 | 283 | core.print_stacktrace() {
|
|
0 commit comments