ruby – 覆盖Sinatra默认的NotFound错误页面

前端之家收集整理的这篇文章主要介绍了ruby – 覆盖Sinatra默认的NotFound错误页面前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有办法覆盖sinatra默认的NotFound错误页面(“Sinatra不知道这个ditty”)?我希望sinatra在没有找到正确的路由时,只显示一个纯粹的字符串为“方法未找到”,但是当我从路由内部引发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块覆盖我的错误消息.

解决方法

也许比 the accepted answer中提出的更为优雅的解决方案是仅救出Sinatra :: NotFound,而不是使用错误(404)或not_found样式.
error Sinatra::NotFound do
  content_type 'text/plain'
  [404,'Not Found']
end

这样就阻止了你没有定义的路由的“sinatra不知道这个ditty”的默认页面,但并不妨碍显式返回[404,“Something else”] – 样式响应.

原文链接:https://www.f2er.com/ruby/266808.html

猜你在找的Ruby相关文章