简体   繁体   中英

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


<%= 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. It seems like StockQuote::Stock.quote does not return nil if the stock symbol in params[:ticker] does not exist but raises an exception.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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