@nanlei/error-handling
TypeScript icon, indicating that this package has built-in type declarations

2.0.1 • Public • Published

error-handling

npm version

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

Readme

Keywords

Package Sidebar

Install

npm i @nanlei/error-handling

Weekly Downloads

1

Version

2.0.1

License

ISC

Unpacked Size

22.9 kB

Total Files

12

Last publish

Collaborators

  • nanlei2000