繁体   English   中英

有没有更好的方法来取消当前请求并重定向到Rails中的错误页面?

[英]Is there a better way cancel the current request and redirect to an error page in Rails?

通常,当我处理控制器我已经找到了需要停止当前的操作,然后显示一个错误页面。 目前,我必须展示在应用控制器我的错误页面的方法:

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

不过我不喜欢有包括and return沿着我的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

raise NotFoundError, msgApplicationController或其子级的任何操作中raise NotFoundError, msg将停止该操作并呈现404.html文件,并返回HTTP错误404。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM