首页 > 解决方案 > 嵌套 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 %>

错误

标签: ruby-on-railsruby

解决方案


查看错误消息,您对工作方式的假设似乎StockQuote::Stock.quote是不正确的。如果股票代码不存在但引发异常,似乎StockQuote::Stock.quote不会返回。nilparams[: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

对于更量身定制的错误处理,您需要提供日志文件中的完整错误消息,包括堆栈跟踪。


推荐阅读