ruby - 绕过 Sinatra 中的 not_found 过滤器
问题描述
我正在尝试将 Sinatra 配置为
- 在所有未找到的请求中显示一个简单的 404 字符串。
- 当路由无法满足请求时,在一个路由中发送自定义 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 过滤器”,或者任何其他更合适的方式来实现这一点?
请记住,实际上,此服务器应返回未找到的视频文件,而不是文本文件。为了简单起见,我在这里使用了文本。
解决方案
正如文档所述,这不是错误,
当
Sinatra::NotFound
引发异常或响应的状态码为 404 时,将not_found
调用处理程序:
我想你可以通过用not_found
这样的错误处理替换覆盖来解决问题:
error Sinatra::NotFound do
content_type :text
"404 Not Found"
end
这应该只在错误时触发,而不是在响应代码上触发。
推荐阅读
- python - 扩展颜色条以包含超出范围的数据
- c# - 变量可以用作C#中的索引号吗?
- python - 对指定像素执行不同的邻域运算
- excel - 受保护工作表上的 ActiveSheet.Paste 错误 [已解决]
- ios - App Center 未显示 Xcode/TestFlight 分发的崩溃
- javascript - !固定的!在 discord.js 中启动时如何在频道中发送消息"
- python - 使用 for 循环从 tkinter 复选框创建和获取值
- python - 在 python 类中包装 ctypes 结构会导致内存错误
- reactjs - 如何在 AWS S3 对象上实现复杂的静态文件缓存(CreateReactApp 构建输出)?
- c - 给定 -hour AM/PM 格式的时间,将其转换为军用(24 小时)时间