You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ubuntu 20.04环境下如何从ldapjs 3.0.5获取详细LDAP错误信息?

问题描述

工作环境为Ubuntu 20.04 + openLDAP 2.4.49,使用ldapjs 3.0.5修改密码时碰到以下问题:

  • 用命令行工具ldappasswd短时间内重复修改密码,能获取详细错误提示:
Result: Constraint violation (19)
Additional info: Password is too young to change
  • 但用ldapjs代码修改时,仅返回ConstraintViolationError错误类型,拿不到上述详细错误描述,代码如下:
'use strict';

const ldap = require('ldapjs');

const client = ldap.createClient({
  socketPath: '/run/ldapi',
});

function changePassword() {
  const userDN = <user_DN>;
  const userPassword = <userPassword>;

  return new Promise((resolve, reject) => {
    client.bind(userDN, userPassword, (err) => {
      if (err) {
        return reject(err);
      } else {
        const change = new ldap.Change({
          operation: 'replace',
          modification: {
            type: 'userPassword',
            values: ['NewPassword'],
          }
        });

        client.modify(userDN, change, err => {
          if (err) {
            return reject(err);
          }

          return resolve();
        });
      }
    })
  });
}

(async () => {
  try {
    await changePassword();
  } catch (e) {
    console.log(`${JSON.stringify(e)}`);
  }

  client.unbind();
})();
解决方法

ldapjs抛出的LDAP错误对象(包括ConstraintViolationError)自带多个属性,其中**diagnosticMessage**字段会存储openLDAP返回的详细错误描述(比如"Password is too young to change"),description属性也会包含简化的错误说明。

修改catch块的代码,直接访问这些属性就能拿到详细信息:

(async () => {
  try {
    await changePassword();
  } catch (e) {
    // 按需打印错误信息
    console.log(`错误类型: ${e.name}`);
    console.log(`LDAP错误码: ${e.ldapErrorCode}`);
    console.log(`详细错误描述: ${e.diagnosticMessage || e.description}`);
    // 或者直接调用toString(),默认会整合关键错误信息
    console.log(e.toString());
  }

  client.unbind();
})();

之所以之前拿不到详细信息,是因为JSON.stringify()序列化错误对象时,只会输出部分默认属性,直接访问错误对象的特定字段才能获取openLDAP返回的完整诊断内容。

内容的提问来源于stack exchange,提问作者James Kim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 05:10:27