NodeJ中的异常处理

时间:2017-03-15 08:34:36

标签: node.js error-handling exception-handling ldapjs

我有以下代码使用ldapjs进行LDAP身份验证。当密码错误时,我会收到错误。我想处理响应中返回的不同错误。

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)
    }

当密码错误时,我的响应低于响应。

 { 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 }.

如何在代码中处理InvalidCredentialsError? 除此之外,如果有任何其他例外,我也想处理它。如何在NodeJs中做到这一点?

1 个答案:

答案 0 :(得分:0)

try { ... } catch (e) { ... }不适用于异步函数。 为此,最佳做法是使用promise和catch函数。就你的例子而言,就像那样:

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);
});;