2.0.1 • Published 5 years ago

@nanlei/error-handling v2.0.1

Weekly downloads
5
License
ISC
Repository
github
Last release
5 years ago

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

5 years ago

2.0.0

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago