2016-08-30 167 views
2

如果验证失败或参数丢失,我想从我的控制器返回400 - bad request。所以,在我的控制器如果有Rails 4.2 ActionController:BadRequest自定义错误消息

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

和我赶上这个错误在我的应用程序控制器,具有:

rescue_from ActionController::BadRequest, with: :bad_request 


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

但好像养ActionController::BadRequest当我不能添加自定义消息。因为当传递一个无效的主体时,响应只有{"error":"ActionController::BadRequest"}而不是我提供的散列。

在控制台中,我得到了相同的行为。 raise ActiveRecord::RecordNotFound, "foo"的确提高了ActiveRecord::RecordNotFound: foo

raise ActionController::BadRequest, "baa"结果

ActionController::BadRequest: ActionController::BadRequest

我如何可以添加自定义消息到BadRequest例外?

回答

2

试试这个:

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