[英]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, msg
在ApplicationController
或其子級的任何操作中raise NotFoundError, msg
將停止該操作並呈現404.html
文件,並返回HTTP錯誤404。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.