如何在Sinatra应用的外部模块中使用error方法实现错误处理
错误原因
error 是 Sinatra::Base 提供的类级方法,普通自定义Helper模块的作用域下不存在该方法,你想要复用错误处理逻辑,需要使用Sinatra扩展(Extension)的规范写法,而不是普通Helper模块的写法。
修改方案
1. 重写application_helper.rb,按Sinatra扩展规范实现
# application_helper.rb require 'sinatra/base' module Sinatra module ApplicationHelper # Sinatra扩展注册钩子,扩展被注册到应用时自动执行 def self.registered(app) # 通过传入的app对象调用error方法注册全局错误处理 app.error StandardError do |e| handle_error 500, e end end # 这里定义的方法会自动作为控制器/路由的实例方法可用 def handle_error(status, exception) # 你的错误处理逻辑示例,可自行修改 halt status, "出现错误:#{exception.message}" end end end
2. 修改控制器中注册模块的方式
把原来的helpers调用改成register,用来注册Sinatra扩展:
# application_controller.rb require './application_helper' class ApplicationController < Sinatra::Base register Sinatra::ApplicationHelper end
如果需要同时保留普通视图Helper方法,只需要在registered方法内追加app.helpers Sinatra::ApplicationHelper即可,无需拆分模块。
内容的提问来源于stack exchange,提问作者Abdel P.
相关产品推荐
相关产品推荐

