简体   繁体   English

轨道上的嵌套 if 语句 ruby 抛出错误

[英]Nested if statements ruby on rails throw error

I try to apply this, bur the webpage sent me error in @stock = StockQuote::Stock.quote(params[:ticker]) when I write in the form something that does not exist, instead the message.我尝试应用这个,当我在表单中写一些不存在的东西而不是消息时,网页在@stock = StockQuote::Stock.quote(params[:ticker])中向我发送了错误。 When I don´t write anything or I write the correct characters, the code works ok, just when I write something wrong on purpose for testing, is when this happens.当我什么都不写或者我写了正确的字符时,代码可以正常工作,就在我故意写错东西进行测试时,就会发生这种情况。 Any advice?有什么建议吗?

method方法

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 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 %>

ERROR错误

Looking at the error message it seems like your assumption of how StockQuote::Stock.quote works is incorrect.查看错误消息,您对StockQuote::Stock.quote工作方式的假设似乎是不正确的。 It seems like StockQuote::Stock.quote does not return nil if the stock symbol in params[:ticker] does not exist but raises an exception.如果params[:ticker]中的股票代码不存在但引发异常,则StockQuote::Stock.quote似乎不会返回nil

A quick and dirty workaround might be to change this part一个快速而肮脏的解决方法可能是更改这部分

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

to

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

For more tailored error handling you would need to provide the full error message from your log fil including the stack trace.对于更量身定制的错误处理,您需要提供来自日志文件的完整错误消息,包括堆栈跟踪。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM