easy-error-ts
TypeScript icon, indicating that this package has built-in type declarations

1.0.21 • Public • Published

EasyError 🚨

EasyError is a lightweight TypeScript library for handling Either types and custom errors design for express. manage your errors without importing or drilling with your res :)

Project Prerequisites ⚙️

  • Node.js
  • npm
  • Visual Studio Code

Installation 📦

npm install easy-error-ts

Usage 🚀

Importing 🔗

import { EasyCustomError, EasyLeft, EasyRight, EasyEither, left, right } from 'easy-error-ts';

Creating Either instances 🔧

Creating a Left instance

const leftValue: EasyLeft<number> = left(42);

Creating a Right instance

const rightValue: EasyRight<EasyCustomError> = right(500, 'Internal Server Error');

Working with Either instances 🛠️

easy to use contains only an EasyEither type for your return and a left and right functions the left is for the good result and the right is for the error. EasyEither is only a type for your return or others.

const fetchMyData = async () : Promise<EasyEither<unknown>> => {
 try {
    const req = await fetch(
        `https://toto.com/api`
    );
    if (!req.ok) {
      return right(500 , `Error message`)
    }
    return left(await req.json())
  } catch (error) {
    return right(500 , `Error message`)
  }
}

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<unknown | CustomError>
) {

  const dataOrError = await fetchMyData();

  const [data, error] = dataOrError;
  return data !== undefined
    ? res.status(200).json({ data })
    : res.status(error?.code ?? 500).json(error ?? { message: 'Internal Server Error' });
}

Contributing 🤝

We welcome contributions! Feel free to open issues or pull requests.

License 📝

This project is licensed under the MIT License - see the LICENSE.md file for details.

Package Sidebar

Install

npm i easy-error-ts

Weekly Downloads

0

Version

1.0.21

License

ISC

Unpacked Size

19.1 kB

Total Files

9

Last publish

Collaborators

  • guillaumegaillard