@japan-d2/error-handler
v0.0.4
Published
A type-safe error handling library that can automatically re-throw unhandled errors.
Downloads
2
Readme
error-handler
A type-safe error handling library that can automatically re-throw unhandled errors.
install
npm install @japan-d2/error-handler
or
yarn add @japan-d2/error-handler
usage
Error Class Designing
NOTE: It does not work when transpiring to es5 or lower.
class BaseError extends Error {
constructor () {
super(code)
this.name = this.constructor.name
}
}
class NetworkError extends BaseError {}
Handling
import { handleExpectedErrors } from '@japan-d2/error-handler'
try {
throw new NetworkError()
} catch (error) {
handleExpectedErrors(error, ({ handleError }) => {
handleError(Error, (e) => {
// only first matched handler will be called
expectedToCall()
})
handleError(NetworkError, (e) => {
doNotCall()
})
})
}
Pass-Through
import { handleExpectedErrors } from '@japan-d2/error-handler'
try {
throw new NetworkError()
} catch (error) {
handleExpectedErrors(error, ({ handleError, pass }) => {
handleError(Error, (e) => {
// umm... I give up handling.
pass()
})
handleError(NetworkError, (e) => {
// to be called
expectedToCall()
})
})
}
Result
Returning a value in handleError
will also propagate to the return value of handleExpectedErrors
.
import { handleExpectedErrors } from '@japan-d2/error-handler'
try {
throw new NetworkError()
} catch (error) {
return handleExpectedErrors(error, ({ handleError, pass }) => {
handleError(Error, (e) => {
return {
statusCode: 500,
body: JSON.stringify({
message: e.message,
})
}
})
})
}
Options
throwIfUnhandled: boolean (default = true)
import { handleExpectedErrors } from '@japan-d2/error-handler'
try {
(undefined as any).hello()
} catch (error) {
handleExpectedErrors(error, ({ handleError }) => {
handleError(NetworkError, (e) => {
console.error(e)
})
}, { throwIfUnhandled: false })
// please handle manually...
}
license
MIT