Exception System Interoperability

How to translate explicit-exceptions to a different exception system.

You may wish to keep explicit-exceptions as an internal detail to your package, and keep your package users unaware of its use. We recommend creating a helper function that does this translation for you, then applying this helper function to every function you export. The following code snippet shows an example of how one would translate explicit exceptions into a custom Error instance (distinguished by a code property).

index.js
const { unwrap } = require('explicit-exceptions')

const { fn1, fn2 } = require('./fileFromPackage')
const { fn3 } = require('./anotherFileFromPackage')

class PackageException extends Error {
  constructor(code, message) {
    super(message)
    this.name = 'PackageException'
    this.code = code
    this.message = message
  }
}

function translateExceptions(fn, expectedExceptions) {
  return (...args) => {
    try {
      return unwrap(fn(...args), expectedExceptions)
    } catch (ex) {
      if (!(ex instanceof Exception)) throw ex
      throw new PackageException(ex.code, ex.message)
    }
  }
}

module.exports = {
  fn1: translateExceptions(fn1, ['NotFound']),
  fn2: translateExceptions(fn2, ['AlreadyExists']),
  fn3: translateExceptions(fn3, ['UserNotFound', 'GroupNotFound']),
  PackageException,
}

A similar solution can be created if you wish to make a different subclass for each kind of exception instead.

Last updated