【问题标题】:How to handle error in ldapjs search method如何处理ldapjs搜索方法中的错误
【发布时间】:2020-11-02 10:54:32
【问题描述】:

我必须连接到 LDAP 服务器并根据特定 ID 查找用户。

我决定使用 ldapjs 模块。

我设法创建了我的客户端并绑定了他,以便我可以成功搜索用户。

我的问题是,因为我只使用 async/await,所以我不明白如何处理回调中的错误...例如使用 ldapjs 库中的这个简单代码:

public static async search(searchOptions: SearchOptions) {
    LdapService.bind()

    LdapService.getClient()?.search('ou=*****,ou=***,dc=****,dc=****', searchOptions, function (err, res) {
      ifError(err)

      res.on('searchEntry', function (entry) {
        // ----------------------
        // an error came from here
        throw new Error('test') 
        // ----------------------

        console.log('entry: ' + JSON.stringify(entry.object));
      });

      res.on('searchReference', function (referral) {
        console.log('referral: ' + referral.uris.join());
      });

      res.on('error', function (err) {
        console.error('error: ' + err.message);
      });

      res.on('end', function (result) {
        console.log('status: ' + result?.status);
      });
    })
  }

LdapService.getClient() 是一个返回 createClient 结果的单例方法 -> 工作正常

LdapService.bind() 是一种仅使用正确凭据与服务器绑定的方法 -> 工作正常

我只是无法处理我的错误“测试”...我应该如何处理它?

搜索方法真的是异步的吗?

我可以使用异步/等待方式吗? :P

PS:由于安全原因,DN 字符串 ("ou=,ou=,dc=,dc=") 被隐藏,代码运行良好,不会引发错误;)

【问题讨论】:

    标签: javascript node.js ldapjs


    【解决方案1】:

    对于任何路过这里并像我一样在回调中苦苦挣扎的人,这里是我找到的“修复”:

    public static async search(searchOptions: SearchOptions) {
        // wrapping the all thing in a Promise that can be in a try/catch -> error will be handled there
        return await new Promise((resolve, reject) => {
          LdapService.getClient()?.search('ou=****,ou=****,dc=****,dc=****', searchOptions, function (err, res) {
            if (err) {
              // handle connection error I guess ?
              reject(err)
            }
    
            res.on('searchEntry', function (entry) {
              try {
                // -------------
                // Same test as before
                throw new Error('test')
                // -------------
    
                resolve(JSON.stringify(entry.object))
              } catch (err) {
                // error must be catched to call reject method !
                reject(err)
              }
            });
    
            res.on('error', function (err) {
              // handle API error when looking for the specific ID I guess ?
              reject(err)
            });
          })
        })
      }
    

    什么解决了我的问题?将所有内容包装在 Promise 中。

    之前的所有“res.on”方法都类似于 Promise 监听器。所以所有方法搜索(我里面的那个)是一种异步调用。

    现在我可以调用 resolve/reject 方法来返回数据和错误。

    另外,我可以将我的静态搜索方法称为 async/await 方式。

    当你不熟悉回调时... ^^"

    【讨论】:

    • 我还删除了所有未使用的“res.on”方法!也许有更短的方法,但这个方法有效;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-10
    • 2011-11-04
    • 2011-05-02
    • 1970-01-01
    • 1970-01-01
    • 2011-10-27
    相关资源
    最近更新 更多