@nanlei/error-handling
v2.0.1
Published
functional error handling like go and rust
Downloads
3
Readme
error-handling
usage
- safe and type safe access nested properties
import { tryCatch } from "@nanlei/error-handling";
const object: {
a?: {
b?: {
c?: string;
};
};
} = {};
const value = tryCatch(() => object!.a!.b!.c!).unwrapOr('ok'); // ok;
- narrow the
Result
type
import { Result } from '@nanlei/error-handling';
const res: Result<number, Error> = tryCatch(() => JSON.parse('\\'));
if (res.isErr === true) {
// value is `undefined` here
console.error(res.error);
} else {
// value is `number` here
console.log(res.value);
}
- define a method return a
Result
type
function mayFail(): Result<number, Error> {
return tryCatch(() => {
if (Math.random() < 0.5) {
return 0;
} else {
throw new Error('too big');
}
});
}
- Use
Match
import { tryCatch, Match } from "@nanlei/error-handling";
const result = tryCatch(() => {
return 1 + 1;
});
Match(result)({
Ok: value => {
console.log(value);
},
Err: (err) => console.error(err)
});