1.0.0 • Published 8 years ago
@anandsuresh/smart-error v1.0.0
smart-error
A SmartError is a wrapper around the JavaScript Error class providing a few additional fields:
code: A unique code identifying the errormetadata: Optional metadata useful for debugging (e.g. the arguments passed to the function that threw the error)cause: An optional error that is being wrapped by theSmartError
usage
const {create} = require('@anandsuresh/smart-error')
const MyError = create('MyError', {
Unexpected: 'An unexpected error occurred.',
BadArguments: 'One or more arguments passed were invalid.',
TimedOut: 'A timeout occurred waiting for the operation to complete.'
})
function isOddNumber(number) {
if (typeof number !== 'number')
throw MyError.BadArguments(number)
return (number % 2 === 0)
}
try {
console.log(`isOddNumber(3) = ${isOddNumber(3)}`)
} catch (e) {
if (e.isBadArguments) {
console.error(`The argument $(e.metadata) is not a number!`)
} else {
console.error(e.toDetailedString())
}
}api
create(errorName, errors)
create takes 2 arguments:
errorName: the name of the error. E.g.'MyError'errors: an object mapping error codes to error messages. E.g.{Unexpected: 'An unexpected error occurred'}
The create() function creates a static function for each error code and an getter function to check if that is the specific error wrapped by the SmartError. Consider the following example:
const {create} = require('@anandsuresh/smart-error')
const MyError = create('MyError', {
Unexpected: 'An unexpected error occurred.',
BadArguments: 'One or more arguments passed were invalid.',
TimedOut: 'A timeout occurred waiting for the operation to complete.'
})The newly created MyError class will inherit from the JavaScript Error class and have the following instance properties:
name: The name of the error, in this case'MyError'code: The unique code of the error (Unexpected,BadArguments,TimedOut)message: A human-readable error messagemetadata: Optional metadata associated with the error (e.g. the arguments passed to the function that threw the error)cause: An optional error that is being wrapped by theSmartErrorstack: The stack-trace generated by the errorisSmartError: Helper property that wraps aninstanceofcheck to return whether or not the instance is aSmartErrorisUnexpected: Helper property that returnstrueif theMyErrorinstance has the codeUnexpectedisBadArguments: Helper property that returnstrueif theMyErrorinstance has the codeBadArgumentsisTimedOut: Helper property that returnstrueif theMyErrorinstance has the codeTimedOut
MyError will also receive the following set of class methods:
Unexpected(metadata, cause): Creates an returns an instance ofMyErrorwith thecodeproperty set toUnexpectedBadArguments(metadata, cause): Creates an returns an instance ofMyErrorwith thecodeproperty set toBadArgumentsTimedOut(metadata, cause): Creates an returns an instance ofMyErrorwith thecodeproperty set toTimedOut
1.0.0
8 years ago