Reputation: 5380
Sometimes I get this error, and I just want Rails to rescue/skip the error when it happens rather than stop the program completely. Is there a good way to do this?
Below is my code:
<% wiki = MediaWiki.new(:domain => 'commons.wikimedia.org') %>
<% wikimedia_user = wiki.find("File:Samuel_L_Jackson_as_Nick_Fury.jpg") %>
The second line causes this error:
NoMethodError (undefined method `first' for nil:NilClass)
If that happens, I just want wikimedia_user
to be set to nil. I tried adding .inspect?
to the end of the .find
, but all I get is the error. Is there a way to do this?
Upvotes: 0
Views: 1670
Reputation: 28574
On the same line as the one you want to suppress the exception and return nil on, add rescue nil
to the end.
<% wikimedia_user = wiki.find("File:Samuel_L_Jackson_as_Nick_Fury.jpg") rescue nil %>
Note: This isn't generally considered a good practice, as any kind of exception thrown from that line will be caught by that rescue. In your case, it's probably not a big problem, but something to keep in mind moving forward.
Upvotes: 3