TransWikia.com

ruby how to stop the execution after rescue

Stack Overflow Asked by Jill448 on December 22, 2021

I have a func where when an exception was raised, I am rescuing it.
But the program continues to the next line and calls the next func create_request

But when there is exception, I do not want to continue

def  validate_request_code options    
  if check_everything is good
     #code to validate
  else
   errors << "something is gone bad"
  end
[errors.size == 0, errors.size == 0 ? options : raise(ArgumentError, "Error while validating #{errors}")]
end

I am trying to catch/rescue the exception

def validate_request options

  begin
   validate_request_code options
  rescue ArgumentError => e
      log :error
  rescue Exception => e
      log :error 
  end

  sleep 20
  
  if options['action'] == "create"
    create_request options
  end
end

One Answer

If by 'not continue' you mean that you want the original error to continue (i.e., you just want to take action on the way by), you can call raise inside the rescue block, which re-raises the original error.

def foo
  begin
    # stuff
  rescue StandardError => e
    # handle error
    raise  
  end
end

You can also simply return from within the rescue block as well.

def foo
  begin
    # stuff
  rescue StandardError => e
    # handle error
    return some_value  
  end
end

As an aside, generally you want to rescue StandardError rather than Exception. All the things that you can reasonably handle within your application are covered under the StandardError. The things outside that are things like out-of-memory, etc., that are outside your control.

Answered by rmlockerd on December 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP