有没有办法覆盖sinatra默认的NotFound错误页面("Sinatra不知道这个小曲")?我希望sinatra只显示一个普通的字符串作为"找不到方法",当它找不到合适的路由时,但是当我从路由中引发404错误时,我希望它显示传入的错误消息.
像这样实现not_found块:
not_found do
'Method not found.'
end
Run Code Online (Sandbox Code Playgroud)
工作,但它不是一个有效的选项,因为我希望能够从这样的路线抛出我自己的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
Run Code Online (Sandbox Code Playgroud)
但正如预期的那样,not_found块会覆盖我的错误消息.
小智 15
也许比接受答案中提出的更优雅的解决方案是仅拯救Sinatra::NotFound
,而不是使用error(404)
或not_found
风格.
error Sinatra::NotFound do
content_type 'text/plain'
[404, 'Not Found']
end
Run Code Online (Sandbox Code Playgroud)
这可以防止"sinatra不知道这个小曲"默认页面用于您尚未定义的路线,但不会妨碍显return [404, 'Something else']
式风格的响应.
如果您没有在路线中使用错误处理,您可以使用这样的内置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
Run Code Online (Sandbox Code Playgroud)
有一个参数captures
可以保存您的错误.你可以通过它访问它params['captures']
.它是一个数组,在我的测试中它将包含一个单独的元素,它本身就是错误(不是字符串).