2013-05-21 24 views
1

考虑下面的控制器方法:如何在正常控制流中引发Rails 3+中的自定义异常?

def create 
    @client = User.find(params[:client][:id]) 
    respond_to do |format| 
     if @client.present? && @client.add_manager(current_user) 
     format.html { redirect_to clients_path, notice: "Successfully added manager" } 
     else 
     format.html { redirect_to clients_path, error: "Could not find client" } 
     end 
    end 
    end 

我如何得到这个在其他块正确失败而不是抛出抛出一个RuntimeError它变成了对生产“出事了”?

def add_manager(user) 
    raise "Already a manager" if self.manager_users.include?(user) 
    self.manager_users << user if user.trainer? 
    end 

是代码...

回答

0

你可以尝试这样的事情:

在你的控制器现在

class YourAppName::AlreadyManagerError < StandardError 

end 

改变 “已经是经理” 去你的名字自定义错误

def add_manager(user) 
    raise YourAppName::AlreadyManagerError if self.manager_users.include?(user) 
    self.manager_users << user if user.trainer? 
end  

然后在你的ApplicationController中

rescue_from YourAppName::AlreadyManagerError do |exception| 
    render :nothing => "Already a manager", :status => 404 
end 

article更详细。另外检查出rescue_from

+0

轨道如何控制流如响应阻塞if和然后#save在该记录上导致它击中真正的if块,然后为重定向false?我只是想用我自己的方法遵循相同的模式。 –

相关问题