ruby-on-rails - 嵌套 if 语句 ruby on rails 抛出错误
问题描述
我尝试应用这个,@stock = StockQuote::Stock.quote(params[:ticker])
当我在表单中写一些不存在的东西时,网页向我发送了错误,而不是消息。当我什么都不写或者我写了正确的字符时,代码可以正常工作,就在我故意写错东西进行测试时,就会发生这种情况。有什么建议吗?
方法
class HomeController < ApplicationController
def index
@stock = StockQuote::Stock.new(api_key: 'pk_7716557806964d85bbd63ceab9bbcbb2')
if params[:ticker] == ''
@nothing = 'Sorry, you forgot to write something, LOL'
elsif params[:ticker]
@stock = StockQuote::Stock.quote(params[:ticker])
if !@stock
@error = "Sorry, maybe you should try again, the symbol you wrote doesn't exist"
end
end
end
def about
end
def lookup
end
end
html
<%= form_tag root_path, :method => 'POST' do %>
<%= text_field_tag 'ticker', nil, placeholder: 'Enter Ticker Symbol', size: 50 %>
<%= submit_tag 'Lookup'%>
<% end %>
<% if @nothing %>
<%= @nothing %>
<% elsif @stock %>
<%= @stock.symbol %><br/>
<%= @stock.company_name %><br/>
<%= number_to_currency(@stock.latest_price , :unit => "$ ") %>
<% if @error %>
<%= @error %>
<% end %>
<% end %>
解决方案
查看错误消息,您对工作方式的假设似乎StockQuote::Stock.quote
是不正确的。如果股票代码不存在但引发异常,似乎StockQuote::Stock.quote
不会返回。nil
params[:ticker]
一个快速而肮脏的解决方法可能是更改这部分
elsif params[:ticker]
@stock = StockQuote::Stock.quote(params[:ticker])
if !@stock
@error = "Sorry, maybe you should try again, the symbol you wrote doesn't exist"
end
end
至
elsif params[:ticker]
begin
@stock = StockQuote::Stock.quote(params[:ticker])
rescue => e
@error = "Sorry, maybe you should try again, the symbol you wrote doesn't exist"
end
end
对于更量身定制的错误处理,您需要提供日志文件中的完整错误消息,包括堆栈跟踪。
推荐阅读
- sql-server - SSIS 脚本任务:错误描述:脚本返回失败结果
- javascript - tf.initializers.constant 不使用数组初始化(Tensorflow js)
- java - 使用 lambda 将二维数组的元素与 Arrays.sort 进行比较
- flutter - 面对未处理的异常:异常:Flutter 中没有 Internet 连接
- javascript - 如何在pointerdown和pointerup上增加和减少进度条值?
- java - 发生配置更改时片段中 OnClickListener 中的空指针异常
- python - 获取 TypeError: 'function' object is not subscriptable 在 API 创建期间出现此错误
- java - JAVA SWING ICEPDF pdf未显示全部内容
- javascript - 如何在不实际应用它们的情况下交付 2 个带导轨的 css
- python - 根据含义相等字符串