Skip to content

Commit 5056859

Browse files
makenowjustRX14
authored andcommittedApr 3, 2018
Pass an unhandled exception to at_exit block as second argument (#5906)
* Pass an unhandled exception to at_exit block as second argument Follow up #1921 It is better in some ways: - it does not need a new exception like `SystemExit`. - it does not break compatibility in most cases because block fill up lacking arguments. * Add documentation for at_exit block arguments * Update `at_exit` block arguments description #5906 (comment) Thank you @jhass.
1 parent 82caaf0 commit 5056859

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed
 

Diff for: ‎spec/std/kernel_spec.cr

+16
Original file line numberDiff line numberDiff line change
@@ -225,4 +225,20 @@ describe "at_exit" do
225225
Unhandled exception: Kaboom!
226226
OUTPUT
227227
end
228+
229+
it "can get unhandled exception in at_exit handler" do
230+
status, _, error = build_and_run <<-CODE
231+
at_exit do |_, ex|
232+
STDERR.puts ex.try &.message
233+
end
234+
235+
raise "Kaboom!"
236+
CODE
237+
238+
status.success?.should be_false
239+
error.should contain <<-OUTPUT
240+
Kaboom!
241+
Unhandled exception: Kaboom!
242+
OUTPUT
243+
end
228244
end

Diff for: ‎src/kernel.cr

+9-3
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ module AtExitHandlers
127127

128128
class_property exception : Exception?
129129

130-
private class_getter(handlers) { [] of Int32 -> }
130+
private class_getter(handlers) { [] of Int32, Exception? -> }
131131

132132
def self.add(handler)
133133
raise "Cannot use at_exit from an at_exit handler" if @@running
@@ -142,7 +142,7 @@ module AtExitHandlers
142142
# Run the registered handlers in reverse order
143143
while handler = handlers.pop?
144144
begin
145-
handler.call status
145+
handler.call status, exception
146146
rescue handler_ex
147147
STDERR.puts "Error running at_exit handler: #{handler_ex}"
148148
status = 1 if status.zero?
@@ -180,7 +180,13 @@ end
180180
# ```text
181181
# goodbye cruel world
182182
# ```
183-
def at_exit(&handler : Int32 ->) : Nil
183+
#
184+
# The exit status code that will be returned by this program is passed to
185+
# the block as its first argument. In case of any unhandled exception, it is
186+
# passed as the second argument to the block, if the program terminates
187+
# normally or `exit(status)` is called explicitly, then the second argument
188+
# will be nil.
189+
def at_exit(&handler : Int32, Exception? ->) : Nil
184190
AtExitHandlers.add(handler)
185191
end
186192

0 commit comments

Comments
 (0)
Please sign in to comment.