4

我正在使用以下代码来检查提供的参数是否正确用于绑定..

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

如果用户和密码不正确,则返回 false,但如果主机或端口号不正确,则显示错误(异常)

 no connection to server (Net::LDAP::LdapError)

我还想捕获此错误,并希望分别为 incoreect 用户/密码和不正确的端口/主机名显示错误消息。我怎样才能做到这一点

4

1 回答 1

0

您可以在此处检查所有可能的异常:https ://www.rubydoc.info/gems/net-ldap/Net/LDAP/Error

但是有些错误不被视为异常,因此您必须使用它们来获取它们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
于 2019-07-05T17:11:42.687 回答