Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 418
theDrifter Avatar asked Aug 30 '16 13:08

theDrifter


1 Answers

Try this:

raise ActionController::BadRequest.new(), "The Json body needs to be wrapped inside a \"Patch\" key"
like image 150
Jonas Avatar answered Sep 21 '22 16:09

Jonas