覆盖Sinatra默认的NotFound错误页面

[英]Override Sinatra default NotFound error page


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.

有没有办法覆盖sinatra默认的NotFound错误页面(“Sinatra不知道这个小曲”)?我希望sinatra只显示一个普通的字符串作为“找不到方法”,当它找不到正确的路由时,但是当我从路由中引发404错误时,我希望它显示传入的错误消息。

Implementing the not_found block like this:

像这样实现not_found块:

 not_found do
    'Method not found.' 
  end

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

工作,但它不是一个有效的选项,因为我希望能够从这样的路由抛出我自己的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

But as expected not_found block overrides my error message.

但正如预期的那样not_found块会覆盖我的错误消息。

3 个解决方案

#1


15  

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.

也许比在接受的答案中提出的更优雅的解决方案是仅拯救Sinatra :: NotFound,而不是使用错误(404)或not_found样式。

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.

这可以防止“sinatra不知道这个小曲”的默认页面用于您尚未定义的路线,但不会妨碍显式返回[404,'Something'] - 样式响应。

#2


5  

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)

如果您没有在路线中使用错误处理,您可以使用这样的内置错误路线(从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

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).

有一个参数捕获可以保存您的错误。您可以通过params ['captures']访问它。它是一个数组,在我的测试中它将包含一个单独的元素,它本身就是错误(不是字符串)。

Here is information on the request object.

以下是有关请求对象的信息。

#3


0  

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.

没关系,发现所有路线都按顺序匹配,所以在我把所有路线都放到/后/放/删除'*'做;结束,这解决了我的问题。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2011/12/09/2f638ce481c46b703e8ff4a619d7d4c0.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号