I m using following code to check whether the provided parameters are correct or not for binding..
require 'rubygems'
require 'net/ldap'
ldap = Net::LDAP.new
ldap.host = your_server_ip_address
ldap.port = 389
ldap.auth "joe_user", "opensesame"
if ldap.bind
# authentication succeeded
else
# authentication failed
end
If user and password is incorrect it returns false but if host or port number is incorrect it displays error (exception)
no connection to server (Net::LDAP::LdapError)
I want to capture this error also and want to show error msg separately for incoreect user/pass and for incorrect port/host name. How can i do this
You can check all possible exceptions here: https://www.rubydoc.info/gems/net-ldap/Net/LDAP/Error
But some errors are not considered exceptions, so you have to get them with get_operation_result
ldap = Net::LDAP.new
begin
ldap.host = '1.2.3.4'
ldap.auth 'cn=config', 'myPassword'
ldap.bind
rescue Net::LDAP::AuthMethodUnsupportedError => e
puts "Net::LDAP::AuthMethodUnsupportedError: #{e}"
rescue Net::LDAP::BindingInformationInvalidError => e
puts "Net::LDAP::BindingInformationInvalidError: #{e}"
rescue Net::LDAP::ConnectionError => e
puts "Net::LDAP::ConnectionError: #{e}"
rescue Net::LDAP::ConnectionRefusedError => e
puts "Net::LDAP::ConnectionRefusedError: #{e}"
rescue Net::LDAP::SocketError => e
puts "Net::LDAP::SocketError: #{e}"
rescue StandardError => e
# Timeout errors are rescued here
puts "StandardError: #{e}"
end
# Wrong user/pass is not an exception and must be checked here
p ldap.get_operation_result
Related
I am trying to get coverage on the following sections of code (from begin to end)in my attached spec where
def process_request(data)
agents = agent_emails(data)
begin
ej = EmailerJob.new(agents: agents, data: data)
CommonLogger.input_log(log_obj,"Sending Lead email to #{agents}")
ej.deliver_emails
rescue Timeout::Error => error
CommonLogger.input_log(log_obj,"#{error}","error")
raise error
rescue StandardError => error
Rails.logger.error "StandardError Handling for #{agents}"
CommonLogger.input_log(log_obj,"#{error}","error")
rescue Exception => error
Rails.logger.error "Exception Handling for #{agents}"
CommonLogger.input_log(log_obj,"#{error}","error")
raise error
end
end
coverage report:
Can somebody please help me how can i cover all rescue sections?
Rspec: 3.12.0
I'm missing something here, but for some reason my begin then rescue Ruby code isn't capturing this error:
#<ActiveResource::ResourceInvalid: Failed. Response code = 422. Response message = Unprocessable Entity.>
This is my code:
begin
ShopifyAPI::CarrierService.create(with some arguments)
rescue StandardError => e
pp e
end
It doesn't ever capture it. In my rescue section I've tried the above but also:
rescue Exception => e
rescue ActiveResource::Errors => e
All with no luck. Where did I go astray?
Thanks
EDIT:
This is the full error, it not really anymore info, but here goes:
#<ShopifyAPI::CarrierService:0x0000000357a0a0
#attributes=
{"name"=>"XXXX",
"callback_url"=>
"https://XX-XX-XX-XX.c9users.io/receive_rate_request",
"format"=>"json",
"service_discovery"=>"true",
"carrier_service_type"=>"api"},
#errors=
#<ActiveResource::Errors:0x00000003578930
#base=#<ShopifyAPI::CarrierService:0x0000000357a0a0 ...>,
#messages={:base=>["you already have XXX set up for this shop"]}>,
#persisted=false,
#prefix_options={},
#remote_errors=
#<ActiveResource::ResourceInvalid: Failed. Response code = 422. Response message = Unprocessable Entity.>,
#validation_context=nil>
That's it!
Because it is not raising an exception, If you want to raise the exception when the response is false, you may have to use create with bang
begin
ShopifyAPI::CarrierService.create!(with some arguments)
rescue StandardError => e
pp e
end
According to the ActiveResource code (lib/active_resource/base.rb):
# <tt>404</tt> is just one of the HTTP error response codes that Active Resource will handle with its own exception. The
# following HTTP response codes will also result in these exceptions:
#
# * 200..399 - Valid response. No exceptions, other than these redirects:
# * 301, 302, 303, 307 - ActiveResource::Redirection
# * 400 - ActiveResource::BadRequest
# * 401 - ActiveResource::UnauthorizedAccess
# * 403 - ActiveResource::ForbiddenAccess
# * 404 - ActiveResource::ResourceNotFound
...
# * 422 - ActiveResource::ResourceInvalid (rescued by save as validation errors)
So it indicates that 422's are rescued by save on validation, which happens when .create is fired, and are bubbled up as validation errors instead.
Looking at lib/active_resource/validations.rb, you can see the ResourceInvalid exception is gobbled:
# Validate a resource and save (POST) it to the remote web service.
# If any local validations fail - the save (POST) will not be attempted.
def save_with_validation(options={})
perform_validation = options[:validate] != false
# clear the remote validations so they don't interfere with the local
# ones. Otherwise we get an endless loop and can never change the
# fields so as to make the resource valid.
#remote_errors = nil
if perform_validation && valid? || !perform_validation
save_without_validation
true
else
false
end
rescue ResourceInvalid => error
# cache the remote errors because every call to <tt>valid?</tt> clears
# all errors. We must keep a copy to add these back after local
# validations.
#remote_errors = error
load_remote_errors(#remote_errors, true)
false
end
So I wonder if it's logging that an exception happened, but is not actually raising an exception because it turns it in to a return false. It does say "local validations" in the comment, but sets remote_errors, so it's not perfectly clear where this code path is executed.
I am using https://github.com/googleads/google-api-ads-ruby/ gem for using adwords api for OfflineConversionFeedService.
Code looks alright:
module AdwordsHelper
def mark_conversion_in_ads(customer)
begin
config_filename = File.join(Rails.root, 'config', 'adwords_api.yml')
adwords = AdwordsApi::Api.new(config_filename)
conversion_feed_srv =
adwords.service(:OfflineConversionFeedService, :v201702)
conversion_time = Time.new.strftime("%Y%m%d %H%M%S")
conversion_value = '100'.to_f
feed = {
:google_click_id => customer.gclid,
:conversion_name => 'LeadCreatedAll',
:conversion_time => conversion_time,
:conversion_value => conversion_value,
:conversion_currency_code => 'GBP'
}
return_feeds = conversion_feed_srv.mutate([
{:operator => 'ADD', :operand => feed}])
return_feeds[:value].each do |return_feed|
puts ("Uploaded offline conversion value %.2f for Google Click ID '%s', " +
'to %s') % [return_feed[:conversion_value],
return_feed[:google_click_id],
return_feed[:conversion_name]]
end
rescue AdwordsApi::Errors::ApiException => e
puts e.backtrace
Logger.log_message("Exception occurred: %s\n%s" % [e.to_s, e.message])
rescue AdsCommon::Errors::OAuth2VerificationRequired => e
puts "Authorization credentials are not valid. Edit adwords_api.yml for " +
"OAuth2 client ID and secret and run misc/setup_oauth2.rb example " +
"to retrieve and store OAuth2 tokens."
puts "See this wiki page for more details:\n\n " +
'https://github.com/googleads/google-api-ads-ruby/wiki/OAuth2'
# HTTP errors.
rescue AdsCommon::Errors::HttpError => e
puts "HTTP Error: %s" % e
# API errors.
rescue AdwordsApi::Errors::ApiException => e
puts "Message: %s" % e.message
puts 'Errors:'
e.errors.each_with_index do |error, index|
puts "\tError [%d]:" % (index + 1)
error.each do |field, value|
puts "\t\t%s: %s" % [field, value]
end
end
end
end
end
My adwords_api.yml file is:
---
:authentication:
:method: OAUTH2_SERVICE_ACCOUNT
:oauth2_keyfile: "/path/to_prod_manager_server_account_file/jsonkey.json"
:developer_token: test_level_developer_token_of_production_manager_account
:client_customer_id: client_customer_id_of_test_manager_account
:oauth2_token:
:access_token: access_token_generated_setup_oauth.rb
:issued_at: 2017-03-16 13:12:25.005441000 +05:30
:expires_in: 3600
:id_token:
:service:
:environment: PRODUCTION
:connection:
:enable_gzip: false
:library:
:log_level: INFO
I have been trying to test this setup for a long time and am getting this error:
Exception occurred: [AuthenticationError.NOT_ADS_USER # ; trigger:'']
[AuthenticationError.NOT_ADS_USER # ; trigger:'']
I have tried a lot of links:
managing test accounts
Can someone please provide exact steps on how to test it out.
For some more clarification, I have Test Account developer key in adwords.
Using adwords api v201702
The api I am trying to use is
OfflineConversion
I am using RestClient to make a network call in the ruby class. I am getting a SocketError whenever I am not connected to the internet. I have added a rescue block to catch the exception still I am not able to do so.
the error message is:
SocketError (Failed to open TCP connection to api.something.com:443 (getaddrinfo: Name or service not known))
module MyProject
class Client
def get_object(url, params={})
response = RestClient.get(url, {params: params})
rescue SocketError => e
puts "In Socket errror"
rescue => e
puts (e.class.inspect)
end
end
end
The broad rescue gets called and print SocketError, but why the previous rescue SocketError is not triggered!
Do you see something that I am missing?
There are a couple of exceptions you'll need to rescue in case you want to fail gracefully.
require 'rest-client'
def get_object(url, params={})
response = RestClient.get(url, {params: params})
rescue RestClient::ResourceNotFound => e
p e.class
rescue SocketError => e
p e.class
rescue Errno::ECONNREFUSED => e
p e.class
end
get_object('https://www.google.com/missing')
get_object('https://dasdkajsdlaadsasd.com')
get_object('dasdkajsdlaadsasd.com')
get_object('invalid')
get_object('127.0.0.1')
Because you can have problems regarding the uri being a 404 destination, or be a domain that doesn't existing, an IP, and so on.
As you can see above, you can have different scenarios that you may encounter when dealing with connecting to a remote uri. The code above rescue from the most common scenarios.
The first one the URL is missing, which is handled by RestClient itself.
The the following three below are invalid domains, which will fail with SocketError (basically a DNS error in this case).
Finally in the last call we try to connect to an IP that has no server running on it - therefore it throws an ERRNO::ECONNREFUSED
I have the following code:
begin
site = RedirectFollower.new(url).resolve
rescue => e
puts e.to_s
return false
end
Which throws errors like:
the scheme http does not accept registry part: www.officedepot.com;
the scheme http does not accept registry part: ww2.google.com/something;
Operation timed out - connect(2)
How can I add in another rescue for all errors that are like the scheme http does not accept registry part?
Since I want to do something other than just printing the error and returning false in that case.
That depends.
I see the three exception descriptions are different. Are the Exception types different as well?
If So you could write your code like this:
begin
site = RedirectFollower.new(url).resolve
rescue ExceptionType1 => e
#do something with exception that throws 'scheme http does not...'
else
#do something with other exceptions
end
If the exception types are the same then you'll still have a single rescue block but will decide what to do based on a regular expression. Perhaps something like:
begin
site = RedirectFollower.new(url).resolve
rescue Exception => e
if e.message =~ /the scheme http does not accept registry part/
#do something with it
end
end
Does this help?
Check what is exception class in case of 'the scheme http does not accept registry part' ( you can do this by puts e.class). I assume that this will be other than 'Operation timed out - connect(2)'
then:
begin
.
rescue YourExceptionClass => e
.
rescue => e
.
end
Important Note: Rescue with wildcard, defaults to StandardError. It will not rescue every error.
For example, SignalException: SIGTERMwill not be rescued with rescue => error. You will have to specifically use rescue SignalException => e.