【发布时间】:2015-07-05 01:10:55
【问题描述】:
我正在尝试处理模块化 Sinatra 应用程序中的错误。我们在整个应用程序中引发了各种错误,我写了一些类似的东西来捕捉错误,认为它会分层发生。
我用来处理错误的文件如下所示。
#!/usr/bin/env ruby
# @class class RApp
# @brief Sinatra main routes overloading for App class
class RApp < Sinatra::Base
# @fn not_found do {{{
# @brief Not found error page
not_found do
render_error 404, _('Not Found'), env['sinatra.error'].message
end # }}}
# @fn error ServiceNotAvailableError do {{{
# @brief Handle ServiceNotFoundException, commonly associated with communication
# errors with external required services like Ambrosia, Saba
error ServiceNotAvailableError do
render_error 503, _('Service Not Available'), env['sinatra.error'].message
end # }}}
# @fn error Exception do {{{
# @brief Handle general internal errors
error Exception do
render_error 500, _('Internal Server Error'), env['sinatra.error'].message
end # }}}
error DBC::InvalidUUIDError do
"Invalid UUID Error"
end
# @fn def show_error code, title, message, view = nil {{{
# @brief Displays the proper message (html or text) based on if the request is XHR or otherwise
def render_error code, title, message, view = nil
view = code.to_s if view.nil?
if request.xhr?
halt code, message
else
halt code, slim(:"error_pages/#{view}", locals: {title: title, message: message})
end
end # }}}
# Just for testing
get '/errors/:type' do |type|
raise Object.const_get(type)
end
end # of class RApp < Sinatra::Base }}}
# vim:ts=2:tw=100:wm=100
我在想它会按照文件中似乎正确的顺序尝试。
问题是Exception 没有捕获所有异常。
例如我有DBC::InvalidUUIDError,就是这样
DBC::InvalidUUIDErrror < DBC::ErrorDBC::Error < RuntimeError- 我理解为 Ruby
RuntimeError < Exception
但它error Exception 并没有像我想的那样捕获所有Exception。
我做错了什么吗?还是一般不能捕获所有异常?
注意:除了提供的答案(两者都有效)之外,我还有set :raise_errors, true。您不需要在开发和生产中设置它。默认情况下,它设置为“测试”环境。
问题的本质是一些异常得到了处理,而另一些则没有。
【问题讨论】:
标签: ruby exception exception-handling sinatra