我正在编写一个带有活动记录的Sinatra http-server。我正在使用pg数据库来存储数据。
在这段代码中,我想要从数据库中获得所有的汽车参数(名称,给他们订单,限制他们),我需要处理来自数据库的错误。
例如,如果我从curl ping‘/car’:
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如何处理来自数据库的异常并将其显示给用户?
发布于 2019-05-31 10:54:44
您需要检查传入的属性参数
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
endhttps://stackoverflow.com/questions/56377121
复制相似问题