ruby 错误页面错误页面

zpgglvta  于 10个月前  发布在  Ruby
关注(0)|答案(4)|浏览(96)

有没有办法覆盖sinatra默认的NotFound错误页面(“Sinatra doesn't know this ditty”)?我希望sinatra在没有找到正确的路由时只显示一个普通的字符串“Method not found”,但当我从路由内部引发404错误时,我希望它显示传入的错误消息。
像这样实现not_found块:

not_found do
    'Method not found.' 
  end

字符串
工作,但它不是一个有效的选项,因为我希望能够像这样从路由抛出自己的NotFound错误消息:

get '/' do
    begin
      # some processing that can raise an exception if resource not found
    rescue => e
      error 404, e.message.to_json
    end
  end


但正如预期的那样,not_found块覆盖了我的错误消息。

nkcskrwz

nkcskrwz1#

也许一个比公认的答案中提出的更优雅的解决方案是只拯救Sinatra::NotFound,而不是使用error(404)not_found样式。

error Sinatra::NotFound do
  content_type 'text/plain'
  [404, 'Not Found']
end

字符串
这可以防止你没有定义的路由出现“sinatra doesn't know this ditty”的默认页面,但不会妨碍return [404, 'Something else']风格的显式响应。

ijxebb2r

ijxebb2r2#

如果你没有在路由中使用错误处理,你可以像这样使用内置的error路由(从Sinatra: Up and Running书中截取并修改)

require 'sinatra'

configure do
  set :show_exceptions, false
end

get '/div_by_zero' do
  0 / 0
  "You won't see me."
end

not_found do
  request.path
end

error do
  "Error is: " + params['captures'].first.inspect
end

字符串
这里有一个参数captures保存你的错误。你可以通过params['captures']访问它。它是一个数组,在我的测试中,它将包含一个元素,这是错误本身(而不是字符串)。
下面是关于请求对象的信息。

ttygqcqt

ttygqcqt3#

没关系,发现所有路由都是按顺序匹配的,所以在所有路由之后我放了get/post/put/delete '*' do ; end,这解决了我的问题。

ncecgwcz

ncecgwcz4#

只需设置RACK_ENV=production来禁用“Sinatra doesn 't know this ditty”页面。Sinatra在生产中使用另一个默认值。
我用的是Sinatra v3.1.0。
但根据Github上的代码,它自2008年(~ v0.3.0)以来就已经实现了,甚至可能更早:

  • https://github.com/sinatra/sinatra/blob/a734cf38ac0e7ddee437c8d273de50f2a4053339/lib/sinatra/base.rb#L638
  • https://github.com/sinatra/sinatra/blob/a734cf38ac0e7ddee437c8d273de50f2a4053339/lib/sinatra/base.rb#L645-L657

相关问题