你可以使用
edariedl
的答案,但更好的方法是在服务器端处理异常:
这里有一个很棒的教程
--
设置
config.exceptions_app = ->(env) { ExceptionController.action(:show).call(env) }
控制器
class ExceptionController < ApplicationController
respond_to :html, :xml, :json
before_action :status
layout :layout_status
def show
respond_with status: @status
end
protected
def status
@exception = env['action_dispatch.exception']
@status = ActionDispatch::ExceptionWrapper.new(env, @exception).status_code
@response = ActionDispatch::ExceptionWrapper.rescue_responses[@exception.class.name]
end
def details
@details ||= {}.tap do |h|
I18n.with_options scope: [:exception, :show, @response], exception_name: @exception.class.name, exception_message: @exception.message do |i18n|
h[:name] = i18n.t "#{@exception.class.name.underscore}.title", default: i18n.t(:title, default: @exception.class.name)
h[:message] = i18n.t "#{@exception.class.name.underscore}.description", default: i18n.t(:description, default: @exception.message)
end
end
end
helper_method :details
private
def layout_status
@status.to_s == "404" ? "application" : "error"
end
end
视图
#app/views/exception/show.html.haml
.box
%h1
= details[:name]
%p
= details[:message]
#app/views/layouts/error.html.haml
!!!
%html
%head
/Info
= meta_tags
/CSS
:css
html {
height: 100%;
background: #fff;
}
body {
font-family: Helvetica, Arial, Sans-Serif;
font-size: 14px;
}
.error_container {
display: block;
margin: auto;
margin: 10% auto 0 auto;
width: 40%;
}
.error_container .error {
display: block;
text-align: center;
}
.error_container .error img {
display: block;
margin: 0 auto 15px auto;
}
.error_container .message > * {
display: block;
}
.error_container .message strong {
font-weight: bold;
color: #f00;
}
.error_container .contact_info {
display: block;
text-align: center;
margin: 25px 0 0 0;
}
.error_container .contact_info a {
display: inline-block;
margin: 0;
opacity: 0.4;
transition: opacity 0.15s ease;
}
.error_container .contact_info a:hover {
opacity: 0.8;
}
/Body
%body
.error_container
= yield
这个结合了一个叫做
ExceptionNotification的 gem,会使你在
staging
和
production
中拥有更强大的异常处理策略。