Override Sinatra default NotFound error page

我怕爱的太早我们不能终老 提交于 2019-12-03 02:47:22
aocole

Perhaps a more graceful solution than that proposed in the accepted answer is to rescue only Sinatra::NotFound, rather than using the error(404) or not_found styles.

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

This prevents the "sinatra doesn't know this ditty" default page for routes that you haven't defined, but doesn't get in the way of explicit return [404, 'Something else']-style responses.

If you don't use error handling in your route, you can utilize the built in error route like this (taken and modified from the Sinatra: Up and Running book)

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

There is a parameter captures that holds your error. You can access it via params['captures']. It is an array, and in my tests it would contain a single element, which was the error itself (not a string).

Here is information on the request object.

Nevermind, found that all routes are matched in order, so after all routes I put get/post/put/delete '*' do ; end and that solves my problem.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!