我正在使用 Sinatra 构建一个小型 Ruby API,我希望将一些错误和配置设置为在全局级别工作,这样我就不需要在每个类。
我的结构是这样的:
content_api.rb
require 'sinatra/base'
require 'sinatra/namespace'
require 'sinatra/json'
require 'service_dependencies'
require 'api_helpers'
require 'json'
module ApiApp
class ContentApi < Sinatra::Base
helpers Sinatra::JSON
helpers ApiApp::ApiHelpers
include ApiApp::ServiceDependencies
before do
content_type :json
end
get '/' do
content = content_service.get_all_content
content.to_json
end
get '/audio' do
package =content_service.get_type 'Audio'
package.to_json
end
get '/video' do
package =content_service.get_type 'Video'
package.to_json
end
get '/document' do
package =content_service.get_type 'Document'
package.to_json
end
end
end
配置.ru:
$LOAD_PATH.unshift *Dir[File.join(File.dirname(__FILE__), '/src/**')]
$LOAD_PATH.unshift *Dir[File.join(File.dirname(__FILE__), '/src/api/**')]
require 'content_api'
require 'package_api'
require 'utility_api'
require 'sinatra/base'
configure do
set :show_exceptions => false
end
error { |err| Rack::Response.new([{'error' => err.message}.to_json], 500, {'Content-type' => 'application/json'}).finish }
Rack::Mount::RouteSet.new do |set|
set.add_route ApiApp::ContentApi, {:path_info => %r{^/catalogue*}}, {}, :catalogue
set.add_route ApiApp::PackageApi, {:path_info => %r{^/package*}}, {}, :package
set.add_route ApiApp::UtilityApi, {:path_info => %r{^/health_check*}}, {}, :health_check
end
当我运行它时,它会正常运行,但是当我强制出现 500 错误(关闭 MongoDb)时,我得到一个标准的 html 类型错误,指出:
<p id="explanation">You're seeing this error because you have
enabled the <code>show_exceptions</code> setting.</p>
如果我添加
configure do
set :show_exceptions => false
end
error { |err| Rack::Response.new([{'error' => err.message}.to_json], 500, {'Content-type' => 'application/json'}).finish }
在 content_api.rb 文件中,然后我收到一个返回的 JSON 错误,正如我希望收到的那样。 然而,当我构建这个模块时,我不想在每个类的顶部重复自己。
有没有一种简单的方法来完成这项工作?
最佳答案
最简单的方法是重新打开 Sinatra::Base
并在其中添加代码:
class Sinatra::Base
set :show_exceptions => false
error { |err|
Rack::Response.new(
[{'error' => err.message}.to_json],
500,
{'Content-type' => 'application/json'}
).finish
}
end
但这可能是不可取的,如果您的应用程序包含其他非 json 模块,将会导致问题。
更好的解决方案可能是创建一个 Sinatra extension你可以在你的模块中使用。
module JsonExceptions
def self.registered(app)
app.set :show_exceptions => false
app.error { |err|
Rack::Response.new(
[{'error' => err.message}.to_json],
500,
{'Content-type' => 'application/json'}
).finish
}
end
end
然后您可以通过在您的模块中注册它来使用它:
# require the file where it is defined first
class ContentApi < Sinatra::Base
register JsonExceptions
# ... as before
end
关于ruby - 模块化 Sinatra App,全局设置错误处理和配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24997214/