Exception System Interoperability
How to translate explicit-exceptions to a different exception system.
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,
}Last updated