覆盖 Sinatra 默认的 NotFound 错误页面

问题描述:

有没有办法覆盖 sinatra 默认的 NotFound 错误页面(Sinatra 不知道这个小东西")?我希望 sinatra 在没有找到正确的路由时只将一个普通字符串显示为未找到方法",但是当我从路由内部引发 404 错误时,我希望它显示传入的错误消息.

Is there a way to override the sinatra default NotFound error page ("Sinatra doesnt know this ditty")? I want sinatra to show only a plain string as "Method not found" when it does not found the proper route, but when I raise an 404 error from inside a route I want it to show the passed-in error message.

像这样实现 not_found 块:

Implementing the not_found block like this:

 not_found do
    'Method not found.' 
  end

有效,但它不是一个有效的选项,因为我希望能够从这样的路由中抛出我自己的 NotFound 错误消息:

works, but its not a valid option since I want to be able to throw my own NotFound error messages from routes like this:

 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 块覆盖了我的错误消息.

But as expected not_found block overrides my error message.

没关系,发现所有路由都是按顺序匹配的,所以在所有路由之后我把 get/post/put/delete '*' do ;结束,这解决了我的问题.

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.