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;
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');
}
});
}
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)
});