0

I have below code to do LDAP authentication using ldapjs. When the password is wrong, I'll get the error. I want to handle different error returned in the response.

var client = ldap.createClient({
                 url: 'ldaps://test.MyCompany.com:939'
              });

 try {
        client.bind('cn=UserName,ou=employees,ou=company users,dc=company,dc=com', "PassWord", function(err, res) {
        console.log(err)
        console.log(typeof err) // prints object
        console.log(err.InvalidCredentialsError)  //prints undefined
        console.log(res);
      });
    } catch (ex) {
      console.log("Exception is", ex)
    }

I'm getting below response when the password is wrong.

 { InvalidCredentialsError: InvalidCredentialsError
[1]     at messageCallback (/Users/Santosh/...../client.js:1419:45)
[1]     at Parser.onMessage (/Users/Santosh/...../client.js:1089:14)
[1]     at emitOne (events.js:96:13)
[1]     at Parser.emit (events.js:191:7)
[1]     at Parser.write (/Users/Santosh/....../parser.js:111:8)
[1]     at TLSSocket.onData (/Users/Santosh/..../client.js:1076:22)
[1]     at emitOne (events.js:96:13)
[1]     at TLSSocket.emit (events.js:191:7)
[1]     at readableAddChunk (_stream_readable.js:176:18)
[1]     at TLSSocket.Readable.push (_stream_readable.js:134:10)
[1]     at TLSWrap.onread (net.js:563:20)
[1]   lde_message: '80090308: LdapErr: DSID-0C0903A8, comment: AcceptSecurityContext error, data 52e, v1db1\u0000',
[1]   lde_dn: null }.

How can I handle InvalidCredentialsError in my code? Along with that if any other exceptions are there also I want to handle that. How to do that in NodeJs?

Santosh Hegde
  • 3,420
  • 10
  • 35
  • 51

1 Answers1

0

The try { ... } catch (e) { ... } don't works with asynchronous functions. To do that, the best practice is to use a promise and the catch function. For your example, it's like that :

let p = new Promise((resolve, reject) => {
    let client = ldap.createClient({
        url: 'ldaps://test.MyCompany.com:939'
    });

    client.bind('cn=UserName,ou=employees,ou=company users,dc=company,dc=com', "PassWord", (err, result) => {
        if (err) {
            reject(err);
            return;
        }
        resolve(result);
    });
});


p.then(result => {
    console.log(result);
}).catch(err => {
    // error returne by reject() or the throwable exception
    console.log(err);
});;
throrin19
  • 17,796
  • 4
  • 32
  • 52