Why controller does not catch error

妖精的绣舞 提交于 2019-12-04 19:36:42

it looks like its catching the error correctly, I am wondering if the real problem is the ordering of the code in the rescue statement. try setting the flash before the render call.

rescue ActiveRecord::RecordNotFound => e
  flash[:error] = e.message
  format.html { render :show }
end

to me, it looks like your returning the error.message and not the render statement. Likewise, you could also try render :show, flash: { error: e.message }

Exception handling starts working when the exception is caught at the respond_to block.

I also defined my own exception, but this has no effect on the result.

def create_user_role
    authorize User
    # Params Inicialization
    role = params[:user][:rolify_role].to_sym
    resource_type = params[:user][:resource_type]
    resource_id = params[:user][:id]

    respond_to do |format|
      begin
        # Make resource as instance of class or set to nil
        resource = RolifyRoles.build_resource(resource_type, resource_id)
        if @user.add_role role, resource
          format.html { redirect_to @user, notice: "Role #{role} was successfully added." }
          format.json { render :show, status: :created, location: @user }
        else
          format.html { render :show }
          format.json { render json: @user.errors, status: :unprocessable_entity }
        end
      # Catch self defined exceptions
      rescue RolifyRolesException => e
        flash[:error] = e.message
        flash.keep
        format.html { render :show, flash: { error: e.message } }
        format.json { render json: e.message, status: :unprocessable_entity }
      end
    end
  end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!