首页 > 解决方案 > 绕过 Sinatra 中的 not_found 过滤器

问题描述

我正在尝试将 Sinatra 配置为

  1. 在所有未找到的请求中显示一个简单的 404 字符串。
  2. 当路由无法满足请求时,在一个路由中发送自定义 404 视频文件。

显示问题的最少代码:

# somefile.txt
some content

# server.rb
require 'sinatra'
require 'sinatra/reloader'

set :bind, '0.0.0.0'
set :port, 3000

not_found do
  content_type :text
  "404 Not Found"
end

get '/test' do
  # in reality this is a video file, not a text file.

  # .. do some work here, and if failed, send 404 file ...

  # this does not work, since it triggers the not_found filter above
  send_file "somefile.txt", type: :text, status: 404

  # this works, but with 200 instead of 404
  # send_file "somefile.txt", type: :text
end

过滤器not_found捕获所有内容,甚至send_file ... status: 404

对我来说,这似乎有点像 中的错误send_file,但也许我错了。

有没有办法声明“跳过 not_found 过滤器”,或者任何其他更合适的方式来实现这一点?

请记住,实际上,此服务器应返回未找到的视频文件,而不是文本文件。为了简单起见,我在这里使用了文本。

标签: rubysinatra

解决方案


正如文档所述,这不是错误,

Sinatra::NotFound引发异常或响应的状态码为 404 时,将not_found调用处理程序:

我想你可以通过用not_found这样的错误处理替换覆盖来解决问题:

error Sinatra::NotFound do
  content_type :text
  "404 Not Found"
end

这应该只在错误时触发,而不是在响应代码上触发。


推荐阅读