theDrifter theDrifter - 7 months ago 31
Ruby Question

How to catch "error":"undefined method `[]' for nil:NilClass"

I have a Rails app for providing a Json REST-Api. In my ApplicationController, I have these lines to catch various errors:

rescue_from ActiveRecord::RecordNotFound, with: :_404
rescue_from ActiveRecord::RecordInvalid, with: :_400
rescue_from ActiveRecord::RecordNotUnique, with: :_406
....
def _404(exception)
Rails.logger.error "head 404 with params #{params}"
render status: 404, :json => {:error => exception.message}
end


In one of my controllers, I have a statement like those where I query the db multiple times for different records.

@account = Account.find_by_phone(params[:phone])
@controller = Controller.find_by_controller_id(params[:role_id])
@batlockers_rel = Batlocker.includes(:customer).where("customer_id is not null")


When I make a call into the controller hitting the specific action, I get the header and the response body

HTTP/1.1 501 NOT IMPLEMENTED
{"error":"undefined method `[]' for nil:NilClass"}


for the requested parameters which are not linked to any database objects.
How do I catch these
NilErrors
, and how can I then include the record which was not found?

Answer

Possibly capture NameError class or more generally StandardError:

rescue_from ::NameError, with: :_whatever
rescue_from StandardError, with: :_whatever

But this types of errors you need to handle yourself, of-cource you need to capture for the first time but you should resolve the error, your app not supposed to throw this kind of errors, check if the data is there before access elements.

Comments