Ruby on rails 有没有更好的方法取消当前请求并重定向到Rails中的错误页面?
在与控制器打交道时,我经常发现需要停止当前操作,然后显示错误页面。目前,我有一种在application controller中显示错误页面的方法:Ruby on rails 有没有更好的方法取消当前请求并重定向到Rails中的错误页面?,ruby-on-rails,ruby,model-view-controller,error-handling,controller,Ruby On Rails,Ruby,Model View Controller,Error Handling,Controller,在与控制器打交道时,我经常发现需要停止当前操作,然后显示错误页面。目前,我有一种在application controller中显示错误页面的方法: class ApplicationController < ActionController::Base def show_error msg render file: 'public/404.html', message: msg, layout: false end end 然后从另一个控制器,我可以这样使用它: c
class ApplicationController < ActionController::Base
def show_error msg
render file: 'public/404.html', message: msg, layout: false
end
end
然后从另一个控制器,我可以这样使用它:
class BikesController < ApplicationController
def inspect
@bike = Bikes.find(params[:id])
show_error("You can't inspect a bike without wheels!") and return unless @bike.hasWheels?
@similar_bikes = Bikes.similar_to(@bike)
render "inspect"
end
end
但是,我不喜欢在show_error方法旁边包含并返回,以确保不执行任何其他操作。有没有一种更干净的方法不使用return就可以做到这一点?Rails处理类似情况的方法是抛出异常并进行处理
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
class NotFoundError < StandardError; end
rescue_from NotFoundError do |e|
render file: "#{RAILS_ROOT}/public/404.html", message: e.message, layout: false, status: :not_found
end
...
end
在ApplicationController或其子级的任何操作中,如果出现raise NotFoundError,msg,则会停止该操作并呈现404.html文件,返回HTTP错误404。no,return是它工作的原因。渲染不会显式返回。