theDrifter
theDrifter

Reputation: 1706

Rails 4.2 ActionController:BadRequest custom error message

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?

Upvotes: 10

Views: 13103

Answers (1)

Jonas
Jonas

Reputation: 5149

Try this:

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

Upvotes: 20

Related Questions