Rails 4.2 ActionController:BadRequest custom error message

theDrifter picture theDrifter · Aug 30, 2016 · Viewed 7.5k times · Source

I want to return from my controller if either a validation failed or a parameter is missing with 400 - bad request. So in my controller if have

if params["patch"].nil? then
  raise ActionController::BadRequest.new( "The Json body needs to be wrapped inside a \"Patch\" key")
end

and i catch this error in my Application Controller with:

rescue_from ActionController::BadRequest, with: :bad_request


def bad_request(exception)
  render status: 400, json: {:error => exception.message}.to_json
end

But it seems like i cannot add custom messages when raising ActionController::BadRequest. Because when passing an invalid body the response is only {"error":"ActionController::BadRequest"} and not the hash i provided.

In the console i get the same behaviour. raise ActiveRecord::RecordNotFound, "foo" indeed raises ActiveRecord::RecordNotFound: foo.

But raise ActionController::BadRequest, "baa" results in

ActionController::BadRequest: ActionController::BadRequest

How can i add custom messages to the BadRequest exception?

Answer

Jonas picture Jonas · Jul 22, 2017

Try this:

raise ActionController::BadRequest.new(), "The Json body needs to be wrapped inside a \"Patch\" key"