@adobe/aio-lib-core-errors

中文文档
4.0.1发布于 2024/02/12Apache-2.0CommonJS零依赖近 30 天下载 12.2万

Adobe I/O SDK Core Errors

原始使用文档
文档目录11 节
  1. Install
  2. Architecture
  3. AioCoreSDKError
  4. Dynamic Errors Usage
  5. Static Errors
  6. 1. Create your Error Class via the ErrorWrapper
  7. 2. Use Your Error Classes
  8. Example Console Output
  9. Explore
  10. Contributing
  11. Licensing

aio-lib-core-errors

Version Downloads/week Node.js CI License Codecov Coverage

This contains the base class for all Adobe I/O Core Errors. Use this as an Error class subclass for all your SDK Errors.

This module was inspired by how Node.js creates its own Error classes.

Install

npm install @adobe/aio-lib-core-errors

Architecture

Adobe I/O Core Error Library Architecture

AioCoreSDKError

This is the base class for all the Error classes, and it should not be instantiated directly. Create your own subclass (dynamic usage) or use the ErrorWrapper below (static usage).

The message property of AioCoreSDKError outputs the Error in this format:

[SDK:ERROR_CODE] ERROR_MESSAGE
  • SDK is the SDK name
  • ERROR_CODE is the error code
  • ERROR_MESSAGE is the error message

Note that the sdk details is not displayed in the message. To see any sdk details, you will need to convert the Error object itself to JSON via .toJSON() (JSON.stringify will convert the Error object as well, via invoking .toJSON() on the Error object)

Dynamic Errors Usage

// Adobe I/O Campaign Standard Wrapper

const { AioCoreSDKError } = require('@adobe/aio-lib-errors')

const gSDKDetails = {
  // ... add your sdk details here
  tenantId,
  endpoint
}
const gSDKName = "AdobeIOCampaignStandard"

export default class CampaignStandardCoreAPIError extends AioCoreSDKError {
  constructor(message, code) {
    // the sdk name and sdk details are curried in as the 3rd and 4th parameters
    super(message, code, gSDKName, gSDKDetails)
  }
}

So if we have this wrapper function, we change from:

function getAllProfiles (parameters) {
    return new Promise((resolve, reject) => {
      const apiFunc = 'getAllProfiles'
      this.sdk.apis.profile[apiFunc]()
        .then(response => {
          resolve(response)
        })
        .catch(err => {
          debug(err)
          // >>>>>TO CHANGE<<<<<<<<<
          reject(new Error(`${apiFunc} ${err}`))
        })
    })
  }

to this:

function getAllProfiles (parameters) {
    return new Promise((resolve, reject) => {
      const apiFunc = 'getAllProfiles'
      this.sdk.apis.profile[apiFunc]()
        .then(response => {
          resolve(response)
        })
        .catch(err => {
          debug(err)
          // >>>>>NEW<<<<<<<<<
          reject(new CampaignStandardCoreAPIError(err.message /* error message */, apiFunc /* error code */))
        })
    })
}

As you can see, this is not very intuitive, and may be error-prone. We can do better with static errors (see below).

Static Errors

The example Usage above is for dynamic errors, for example API errors that we are wrapping. Static errors are much better: they are more intuitive to use, and much better for code readability.

1. Create your Error Class via the ErrorWrapper

We define our specialized Error class, and error codes in its own module like so:

// SDKErrors.js
const { ErrorWrapper, createUpdater } = require('@adobe/aio-lib-core-errors').AioCoreSDKErrorWrapper

const codes = {}
const messages = new Map()

/**
 * Create an Updater for the Error wrapper
 */
const Updater = createUpdater(
  // object that stores the error classes (to be exported)
  codes,
  // Map that stores the error strings (to be exported)
  messages
)

/**
 * Provides a wrapper to easily create classes of a certain name, and values
 */
const E = ErrorWrapper(
  // The class name for your SDK Error. Your Error objects will be these objects
  'MySDKError',
  // The name of your SDK. This will be a property in your Error objects
  'MySDK',
  // the object returned from the CreateUpdater call above
  Updater
  // the base class that your Error class is extending. AioCoreSDKError is the default
  /* , AioCoreSDKError */
)

module.exports = {
  codes,
  messages
}

// Define your error codes with the wrapper
E('UNKNOWN_THING_ID', 'There was a problem with that thing')
E('UNKNOWN_ORDER_ID', 'There was a problem with that order id: %s.')

Error Class Wrapper

Let's parse what this line means:

E('UNKNOWN_ORDER_ID', 'There was a problem with that order id: %s.')

This will dynamically create a MySDKError class with the appropriate closures for values:

  • sdk name (MySDK, passed in to the ErrorWrapper constructor above)
  • sdk error class name (MySDKError, passed in to the ErrorWrapper constructor above)
  • error code (UNKNOWN_ORDER_ID, the first parameter passed in to E)
  • error message (There was a problem with that order id: %s., the second parameter passed in to E. If this is a string with format specifiers, you can pass in arguments for the format specifiers, when the Error is constructed. See example below).
class MySDKError extends AioCoreSDKError { ... }

The line will add the dynamically created MySDKError class to the exported codes object, with the first parameter to the wrapper (the error code) as the key.

The constructor for the class created takes one parameter, an object:

constructor(parameters)
  • parameters (optional) is an object
  • parameters.sdkDetails (optional) is an object that you want to pass in as additional data for the Error object. e.g. function parameters for an API call.
  • parameters.messageValues (optional) is a string, number, object or an array of the items that you want to apply to the error message, if the message has a format specifier.

In the error specification line below, you can see it has one format specifier %s:

E('UNKNOWN_ORDER_ID', 'There was a problem with that order id: %s.')

2. Use Your Error Classes

Import the static error code Error classes, and use directly.

 const { UNKNOWN_THING_ID, UNKNOWN_ORDER_ID } = require('./SDKErrors').codes
// or, if you have too many codes to destructure:
// const { codes } = require('./SDKErrors')

const gSdkDetails = {
  tenantId: 'mytenant'
}
// convoluted examples, but demonstrates usage
const unknownThing = true
if (unknownThing) {
  throw new UNKNOWN_THING_ID({ sdkDetails: gSDKDetails })
}

const unknownOrderId = true
if (unknownOrderId) {
  // messageValues can either be a string, object, etc or an array of them
  throw new UNKNOWN_ORDER_ID({ 
    sdkDetails: gSDKDetails,
    messageValues: ['ORDER-2125SFG']
  }) ) 
}

function getOrder(orderId) {
  // we just wrap the function arguments as the sdkDetails
  const sdkDetails = { orderId }
  const somethingWentWrong = true

  if (somethingWentWrong) {
  // messageValues can either be a string, object, etc or an array of them
    throw new UNKNOWN_ORDER_ID({ 
      sdkDetails: sDKDetails,
      messageValues: 'ORDER-2125SFGF'
    }) ) 
  }
}

getOrder('abc123')

Example Console Output


Print out a thrown UNKNOWN_ORDER_ID Error object to the console. console calls the .toString() method for the Error object, and the resulting data is not structured well, and will not expand nested objects:

try {
  throw new UNKNOWN_ORDER_ID()
} catch (e) {
  console.error(e)
}

Output:

 { MySDKError: [MySDK:UNKNOWN_ORDER_ID] There was a problem with that order id: ORDER-21241-FSFS.
          at new <anonymous> (/Users/obfuscated/aio-lib-core-errors/src/AioCoreSDKErrorWrapper.js:22:9)
          at Object.<anonymous>.test (/Users/obfuscated/aio-lib-core-errors/test/MySDKError.test.js:50:15)
          at Object.asyncJestTest (/Users/obfuscated/aio-lib-core-errors/node_modules/jest-jasmine2/build/jasmineAsyncInstall.js:102:37)
          at resolve (/Users/obfuscated/aio-lib-core-errors/node_modules/jest-jasmine2/build/queueRunner.js:43:12)
          at new Promise (<anonymous>)
          at mapper (/Users/obfuscated/aio-lib-core-errors/node_modules/jest-jasmine2/build/queueRunner.js:26:19)
          at promise.then (/Users/obfuscated/aio-lib-core-errors/node_modules/jest-jasmine2/build/queueRunner.js:73:41)
          at process._tickCallback (internal/process/next_tick.js:68:7)
        code: 'UNKNOWN_ORDER_ID',
        sdk: 'MySDK',
        sdkDetails: { tenantId: 'MYTENANT2' },
        name: 'MySDKError' }

Simply print out a thrown UNKNOWN_ORDER_ID Error object's message property to the console:

try {
  throw new UNKNOWN_ORDER_ID()
} catch (e) {
  console.error(e.message)
}

Output:

[MySDK:UNKNOWN_ORDER_ID] There was a problem with that order id: ORDER-21241-FSFS.

Convert a thrown UNKNOWN_ORDER_ID Error object to JSON and print to the console. console calls the .toJSON() method of the Error object, and will expand nested objects:

try {
  throw new UNKNOWN_ORDER_ID()
} catch (e) {
  console.error(JSON.stringify(e, null, 2))
}

Output:

{
    "sdk": "MySDK",
    "sdkDetails": { "tenantId": "MYTENANT2" },
    "code": "UNKNOWN_ORDER_ID",
    "message": "[MySDK:UNKNOWN_ORDER_ID] There was a problem with that order id: ORDER-21241-FSFS.",
    "stacktrace": "MySDKError: [MySDK:UNKNOWN_ORDER_ID] There was a problem with that order id: ORDER-21241-FSFS.\n    at new <anonymous> (/Users/obfuscated/aio-lib-core-errors/src/AioCoreSDKErrorWrapper.js:22:9)\n    at Object.<anonymous>.test (/Users/obfuscated/aio-lib-core-errors/test/MySDKError.test.js:50:15)\n    at Object.asyncJestTest (/Users/obfuscated/aio-lib-core-errors/node_modules/jest-jasmine2/build/jasmineAsyncInstall.js:102:37)\n    at resolve (/Users/obfuscated/aio-lib-core-errors/node_modules/jest-jasmine2/build/queueRunner.js:43:12)\n    at new Promise (<anonymous>)\n    at mapper (/Users/obfuscated/aio-lib-core-errors/node_modules/jest-jasmine2/build/queueRunner.js:26:19)\n    at promise.then (/Users/obfuscated/aio-lib-core-errors/node_modules/jest-jasmine2/build/queueRunner.js:73:41)\n    at process._tickCallback (internal/process/next_tick.js:68:7)"
}

Explore

goto API

Contributing

Contributions are welcomed! Read the Contributing Guide for more information.

Licensing

This project is licensed under the Apache V2 License. See LICENSE for more information.

版本与发布记录

@adobe/aio-lib-core-errors 共发布 11 个版本,首次发布于 2019/09/16;过去 12 个月发布了 0 个版本。

版本发布日期距今
4.0.1latest2024/02/122 年前
4.0.02024/01/102 年前
3.1.1-pre.2024-01-08.6d76060cnext2024/01/082 年前
3.1.12022/08/224 年前
3.1.02022/08/194 年前
3.0.1-pre.2022-06-06.fe3bb36f2022/06/064 年前

关于 @adobe/aio-lib-core-errors 的常见问题

@adobe/aio-lib-core-errors 是什么?

Adobe I/O SDK Core Errors

如何安装 @adobe/aio-lib-core-errors?

在项目目录运行 npm install @adobe/aio-lib-core-errors,或使用 pnpm add / yarn add / bun add。

@adobe/aio-lib-core-errors 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/adobe__aio-lib-core-errors 是否存在。

@adobe/aio-lib-core-errors 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@adobe/aio-lib-core-errors 可以商用吗?

@adobe/aio-lib-core-errors 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@adobe/aio-lib-core-errors 的下载量有多少?

根据 npm 官方下载统计,@adobe/aio-lib-core-errors 在 2026/10/05 – 2026/11/03 这 30 天内被下载 122,198 次,日均约 4,073 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@adobe/aio-lib-core-errors 还在维护吗?

最新版本 4.0.1 发布于 2024/02/12(2 年前);至今共发布 11 个版本,其中过去 12 个月发布了 0 个;首次发布于 2019/09/16。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。