classApplicationController<ActionController::Baserescue_fromUser::NotAuthorized,:with=>:deny_access# self defined exceptionrescue_fromActiveRecord::RecordInvalid,:with=>:show_errorsrescue_from'MyAppError::Base'do|exception|render:xml=>exception,:status=>500endprotecteddefdeny_access...enddefshow_errors(exception)exception.record.new_record??...endend
require'net/http'classNet::HTTPInternalServerErrordefexception(message="Internal server error")RuntimeError.new(message)endendclassNet::HTTPNotFounddefexception(message="哈囉")RuntimeError.new(message)endendresponse=Net::HTTP.get_response(URI.parse("http://avdi.org/notexist"))ifresponse.code.to_i>=400raiseresponseend
Step 2: #set_backtrace
追蹤錯誤來源
in order to get a stack trace which includes the current line, you must call #caller passing 0 for the “start” parameter
deferrors_with_message(pattern)#Generate an anonymous "matcher module" with a custom threequalsm=Module.new(class<<m;self;end).instance_evaldodefine_method(:===)do|e|pattern===e.messageendendmendputs"About to raise"beginraise"Timeout while reading from socket"rescueerrors_with_message(/socket/)puts"Ignoring socket error"endputs"Continuing..."
A custom exception matcher.
123456789101112131415161718192021222324
deferrors_matching(&block)m=Module.new(class<<m;self;end).instance_evaldodefine_method(:===,&block)endmendclassRetryableError<StandardErrorattr_reader:num_triesdefinitialize(message,num_tries)@num_tries=num_triessuper("#{message} (##{num_tries})")endendputs"About to raise"beginraiseRetryableError.new("Connection timeout",2)rescueerrors_matching{|e|e.num_tries<3}=>eputs"Ignoring #{e.message}"endputs"Continuing..."