【问题标题】:Handling database errors in sinatra处理 sinatra 中的数据库错误
【发布时间】:2019-10-16 01:02:05
【问题描述】:

我正在编写一个带有活动记录的 Sinatra http-server。我正在使用 pg 数据库来存储数据。

在这段代码中,我想从数据库中获取所有带有参数的汽车(名称、给它们排序、限制它们),并且我需要处理来自数据库的错误。

例如,如果我从 curl ping '/cars':

curl -X GET http://localhost:8080/cars?attribute=error

我需要结果: '对不起,没有名称错误的属性'

get '/cars' do    
  @cars = Car.order("#{params[:attribute]} #{params[:order]}").limit(params[:limit]).offset(params[:offset])
  @cars.to_json
 end

如何处理来自数据库的异常并将它们显示给用户?

【问题讨论】:

  • 欢迎来到 SO!首先,不要将查询发送到用户可以自己生成的数据库,否则您将面临被黑客入侵的风险。如果params[:attribute] 包含某种“删除所有内容”或“删除数据库”,您就会遇到麻烦。为了检查结果,我会发送经过验证的查询,看看我是否得到 nil 并有条件地返回 Sinatra 错误。

标签: ruby postgresql sinatra


【解决方案1】:

需要检查传入的属性参数

get '/cars' do   
  if Car.columns.map(&:name).include?(params[:attribute]) 
    @cars = Car.order("#{params[:attribute]} #{params[:order]}")
             .limit(params[:limit]).offset(params[:offset])
    @cars.to_json
  else
    { error: 'Sorry, but there is no attribute with name error' }.to_json
  end
end

【讨论】:

    猜你喜欢
    • 2014-12-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-30
    • 2011-11-03
    相关资源
    最近更新 更多