forked from franzejr/best-ruby
-
Notifications
You must be signed in to change notification settings - Fork 0
/
at_exit_method.rb
47 lines (37 loc) · 913 Bytes
/
at_exit_method.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#Basic use
puts 'script start'
at_exit do
puts 'inside at_exit method for the first time'
end
#anywhere in your code again
at_exit do
puts 'inside at_exit method for the second time'
end
puts "script end"
#Result:
#script start
#script end
#inside at_exit method for the second time
#inside at_exit method for the first time
#Own exception crash logger
at_exit do
if $! # If the program exits due to an exception
puts 'Exiting'
#you can also print log to a file
#you can send notification to another app
end
end
#Logging error anywhere when program exit
(Thread.current[:errors] ||= []) << 'Any error message goes here'
#or
def log_error(error_message)
(Thread.current[:errors] ||= []) << "#{error_message}"
end
#Now, log all the errors
at_exit do
File.open('errors.txt', 'a') do |file|
(Thread.current[:errors] ||= []).each do |error|
file.puts error
end
end
end