-2

I'm using the Microsoft computer vision API. The API can recognise faces and gives data on how many people are in an image, what estimated age they are, and what estimated gender. However, I have a "do" loop which I can't "rescue." Here's the code below:

 values = json_data['faces'].map do |result| 

Here's the error I receive:

C:/Users/KVadher/Desktop/micr1.rb:122:in `block in <main>': undefined method `[]' for nil:NilClass (NoMethodError)

I want my code to look something like this:

 begin
  values = json_data['faces'].map do |result| 
 rescue
 end

However, when I do this, I get the following error:

C:/Users/USERNAME/Desktop/micr1.rb:123: syntax error, unexpected keyword_rescue

How do I pass my code if a request doesn't apply to it?

maazza
  • 7,016
  • 15
  • 63
  • 96
semiflex
  • 1,176
  • 3
  • 25
  • 44

2 Answers2

5

You map block should have end

begin
  values = json_data['faces'].map do |result|
    # ...
  end
rescue
end
spickermann
  • 100,941
  • 9
  • 101
  • 131
Alexander Shlenchack
  • 3,779
  • 6
  • 32
  • 46
2

As Alexander points out, the lack of an end to the do statement explains the unexpected keyword error.

However, using rescue in this way is not good practice. It will effectively mask any problems that occur in the future. You should always be specific in what you rescue. So this would be better:

begin
  values = json_data['faces'].map do |result|
    ...
  end
rescue NoMethodError
end

However, the error is telling you that json_data is nil. So to handle this issue, a simpler solution is:

if json_data
  values = json_data['faces'].map do |result|
     ...
  end
else
  values = [] # or whatever you want values to be if there are none
end
ReggieB
  • 8,100
  • 3
  • 38
  • 46
  • Your code will raise an error when json_data is present and it's not an hash – Alexander Shlenchack Dec 16 '15 at 11:36
  • @AlexanderShlenchack that's true - but emphasises my point. You should build your code to deal with the errors you know about, and let other errors bubble up through the system. The only error mentioned that needs handling programmatically is `json_data == nil`. If json can be something other than hash or nil then that will need to be handled too, but there is nothing in the question that states that to be the case. – ReggieB Dec 16 '15 at 17:34
  • 1
    I completely agree with you. It was my little remark, nothing more. – Alexander Shlenchack Dec 16 '15 at 20:18