errorsasvaluests
v1.0.5
Published
Errors-As-Values Error Handling
Readme
Expected
1. Making an Expected instance
API
static Expected.ok<T>(value: T);
static Expected.fail<E>(value: E);T: The return type
E: The error type
Example
function myFunc(): Expected<void, Error> {
try {
// do work
return Expected.ok(void);
} catch (e) {
return Expected.fail(e);
}
}2. Wrapping a function
API
static Expected.run<T, E>(fn: (...args: unknown[]) => T | Expected<T, E>,
args?: any[],
errorType?: new (...args: any[]) => E): Expected<T, E>fn: The function to call
args?: What arguments to use, if any.
errorType?: The constructor for the error type. If errorType is provided, and the error thrown by the function doesn't match errorType, the error will be propogated outwards rather than returned as a value.
Expected<T, E>.onError(
fn: (
errorValue: E,
setReturnValue: (value: T) => void
) => void
): T | undefinedfn: A handler for any occuring errors
errorValue: The error value
setReturnValue: By default, onError() returns undefined and calls your handler if any error occures, otherwise returning the returned value. For your handler to replace the placeholder undefined, call setReturnValue() with the value you'd like onError to return.
Example
function myFunc(): void {
throw Error("3");
}
const value = Expected.run(myFunc).onError((e, h) => h(Number(e.message))); // 3Tips
If the function returns an instance of Expected, that exact instance will be returned by run().
If the function passed to run() returns any other value, it will get wrapped into Expected.ok(value).
If the function passed to run() throws an error:
- If no errorType constructor is specified, it will get wrapped into
Expected.fail(error) - If an errorType constructor is specified:
- If the error matches the constructor (runtime type validation), it will get wrapped into
Expected.fail(error) - If the error doesn't match the constructor, it will get re-thrown.
- If the error matches the constructor (runtime type validation), it will get wrapped into
- The library provides a
throwError(e)function that throws an error, that you can pass toonError(). However, you should prefergetValueUnsafe()over this to keep code shorter.
3. Leaving errors unhandled
API
static Expected.getValueUnsafe<T>(expected: Expected<T, any>): TReturns the value stored within an Expected instance. If expected is an Expected.fail, then an error will be thrown with the error stored by expected (note: it does not have to be an Error instance).
Good for when you want your program to crash if a function fails, or if you need to maintain backwards-compatibility with a caller.
