@nick-bull/to
v1.0.2
Published
Destructure errors instead of using a `try/catch` block
Downloads
7
Readme
Destructure errors instead of using a try/catch
block. Great for separating error handling concerns and improving readability:
let someConstValue;
try {
someConstValue = await riskyFn();
}
catch (error) {
logger.log(error);
someOther.errorHandlingStuff(error);
}
let anotherConstValue;
try {
anotherConstValue = await riskyFn();
}
catch (error) {
logger.log(error);
someOther.errorHandlingStuff(error);
}
becomes this:
const [ someError, someConstValue ] = await to(riskyFn());
if (someError) return;
const [ anotherError, anotherConstValue ] = await to(riskyFn());
Usage
// Use
import {createTo} from '@nick-bull/to';
// Options to configure behaviour whenever an error occurs
const createOptions = {
// `logger` is a service that exposes a `error(message)` function
logger,
// Any other error concerns in a callback argument
callback: (error) => someOther.errorHandlingStuff(error),
}
const {to, toError, toValue} = createTo(createOptions);
// Or, if you don't need any configuration and you want to handle errors via `if`
import {to, toError, toValue} from '@nick-bull/to';
and to handle an error
const [error, value] = await to(asyncFn());
const justTheError = await toError(asyncFn());
const justTheValue = await toValue(asyncFn());
toValue
may seem a little redundant, and it is unless you've built using createTo
, where it will still perform error concerns such as calling the callback
With @nick-bull/create-error
There's also an option to decorate errors, which is great for when a function outputs error messages which aren't particularly useful (looking at you, Postgresql query
)
import {to, toError, toValue} from '@nick-bull/to';
const niceError = {
name: 'veryNiceError',
message: 'A bad error occurred',
};
const [error, value] = await to(asyncFn(), niceError);
const justTheError = await toError(asyncFn(), niceError);
const justTheValue = await toValue(asyncFn(), niceError);