I'm trying to figure out the best way to catch a specific error thrown AND the error's message in Ruby on Rails. My use case is that I encounter a timeout error every now and then which is thrown with a general error and I want to treat the timeout error differently than other errors within the same general error. I'm not sure what other type of errors could be thrown in the general error but I assume more of them exist. I have some sample code below of how I'm currently handling it, but I was thinking there might be a better way which I haven't found yet?
tries = 0
begin
tries += 1
<code>
rescue Foo::Bar => e
case e.to_s
when 'More specific timeout error message'
retry unless tries >= 5
else
# Let me see other error messages
log.info("Error: #{e.to_s}")
end
end
You can use multi rescue, to handle different errors.
begin
# DO SOMETHING
rescue Net::Timeout => e # change it to the error your want to catch, check the log.
# handle it
rescue SyntaxError => e # just an example
# handle it
rescue => e # any error that not catch by above rescue go here.
# handle it
end
Read more:
http://phrogz.net/programmingruby/tut_exceptions.html
You can try Rollbar, it help report error on production.
Take a look at retriable gem. It seems like a good fit for what you're proposing. Usually you'd rescue from an specific error type, but retriable also gives you the choice to rescue based on the error message.
begin
Retriable.retriable on: { Foo::Bar => /More specific timeout error message/ }, tries: 3 do
# will retry if an error of type Foo::Bar is raised
# and its message matches /More specific timeout error message/
# code here...
end
rescue => e # rescue for everything else
puts e.message # same as e.to_s
end
Related
If a template causes an ActiveRecord::RecordNotFound exception to be raised, the original exception is swallowed up by ActionView and turned into an ActionView::Template::Error.
It seems that in Rails 5 there was an original_exception method but that appears to be gone in Rails 6.
I'd like to be able to inspect the cause of the ActionView::Template::Error so I can show better contextual errors.
Is there any way to do so?
If you catch the ActionView::Template::Error, there should be a #cause method defined on it which returns the original exception. Example:
begin
begin
raise ArgumentError
rescue
raise RuntimeError
end
rescue => e
puts "#{ e } caused by #{ e.cause }"
end
prints
RuntimeError caused by ArgumentError
I have the following code in Rails routing:
class LegacyRedirector
InvalidUrlError = Class.new(ActionController::RoutingError)
def call(params, request)
URI.parse(request.path)
rescue URI::InvalidURIError => e
raise InvalidUrlError.new(e.message)
end
end
# routes.rb
match 'a', to: redirect(LegacyRedirector.new)
This is for catching invaild URLs. However when I test it in browser for curl, it would still display URI::InvalidURIError, not my new error class. It seems the rescue block was never reached, yet I am sure I am rescuing the correct type. How can that be?
URI::InvalidURIError at /twitter/typeahead-js/wikis/home[
=========================================================
> bad URI(is not URI?): "/twitter/typeahead-js/wikis/home["
lib/gitlab/routing.rb, line 31
------------------------------
``` ruby
> 31 URI.parse(request.path)
32 rescue URI::InvalidURIError => e
33 raise InvalidUrlError.new(e.message)
34 end
```
One possible cause could be better_errors.
If an error is raised in a rescue block, its cause would be the original error. better_errors displays that cause instead, meaning the backtrace will not be in the rescue block. This gives you the illusion that it is never rescued.
This was recently fixed, see https://github.com/BetterErrors/better_errors/pull/459 for more details
When debugging failing integration tests, I keep running into the same problem where the exceptions raised in my code are suppressed and not shown in the testing output.
For example, for the following controller and test:
class RegistrationController::ApplicationController
def create
# some code that raises an exception
end
end
class RegistrationFlowTest < ActionDispatch::IntegrationTest
test 'user registers successfully' do
post sign_up_path, params: { username: 'arnold', password: '123' }
assert_response :success
end
end
The output is something like
Minitest::Assertion: Expected response to be a <2XX: success>, but was a <500: Internal Server Error>
Is there a way to see the exact raised exception? Instead of just the difference of HTTP response code?
Thanks!
Simon
My recommended approach to this issue would be to actually parse the response provided by Rails (at least by default in test and development environments) which includes the stacktrace for the error and handle that in the case that your test fails. This has the advantage that it won't output the stacktrace when errors are raised that don't result in failing tests (e.g. scenarios where you are intentionally testing how failures are handled).
This little module that I've crafted will allow you to call assert_response_with_errors to assert the response to a call but output the exception message and stack trace in a readable format when the response is not what you expected.
module ActionDispatch
module Assertions
module CustomResponseAssertions
# Use this method when you want to assert a response body but also print the exception
# and full stack trace to the test console.
# Useful when you are getting errors in integration tests but don't know what they are.
#
# Example:
# user_session.post create_gene_path, params: {...}
# user_session.assert_response_with_errors :created
def assert_response_with_errors(type, message = nil)
assert_response(type, message)
rescue Minitest::Assertion => e
message = e.message
message += "\nException message: #{#response.parsed_body[:exception]}"
stack_trace = #response.parsed_body[:traces][:'Application Trace'].map { |line| line[:trace] }.join "\n"
message += "\nException stack trace start"
message += "\n#{stack_trace}"
message += "\nException stack trace end"
raise Minitest::Assertion, message
end
end
end
end
To use this, you need to include it into ActionDispatch::Assertions before Rails has loaded its stack in your test_helper.rb. So just prepend the include into your test_helper.rb, like this:
ActionDispatch::Assertions.include ActionDispatch::Assertions::CustomResponseAssertions
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
...
This will happen because Rails controllers by default handle exceptions and raise the 500 status, making the exceptions invisible to the test suite (which is very helpful if errors are raised in unit tests of a model). Options for disabling this in your test suite, or alternative workarounds, are discussed here.
The key lines of code from that link, which should be added to test/integration/integration_test_helper.rb:
ActionController::Base.class_eval do
def perform_action
perform_action_without_rescue
end
end
Dispatcher.class_eval do
def self.failsafe_response(output, status, exception = nil)
raise exception
end
end
EDIT: I've noticed that that link is quite old now. I'm really familiar with Rack, so whilst the first block looks ok to me, I'm not sure if the second will still be current. You might need to have a look at the relevant current Rails guide if it needs bringing up to date.
If ERB.new(...).result raises an exception how do I get the code and backtrace near it?
Like rails does with it's templates.
I tried what #Nathan suggested before:
begin
ERB.new('<%= fail %>').result
rescue Exception => e
p e
end
=> RuntimeError
That doesn't tell me the position of the error
Try:
begin
ERB.new(...).result
rescue Exception => e
# puts e
# or
# binding.pry if you use the pry gem
end
When exiting a Rails app using raise or fail, how to prevent the backtrace from being displayed?
Tried using back_trace_limit but it only seems to work for the console...?
You have total control over the backtrace returned with an exception instance by using its set_backtrace method. For example:
def strip_backtrace
yield
rescue => err
err.set_backtrace([])
raise err
end
begin
strip_backtrace do
puts 'hello'
raise 'ERROR!'
end
rescue => err
puts "Error message: #{err.message}"
puts "Error backtrace: #{err.backtrace}"
end
Output:
hello
Error message: ERROR!
Error backtrace: []
The strip_backtrace method here catches all errors, sets the backtrace to an empty array, and re-raises the modified exception.