Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

computer-says-no

codeandcats92MIT0.3.0TypeScript support: included

Super simple type-safe and serializable error management in TypeScript.

error, exception, error handling, error management

readme

Super simple type-safe and serializable error management in TypeScript & JavaScript.

npm GitHub Workflow Status (branch) Coveralls github branch

Install

npm add computer-says-no
yarn add computer-says-no

Features

  • Easy Error definitions and type assertions
  • Works for errors that have been serialized (via an API as JSON)
  • i18n friendly

Usage

Let's pretend we have a login function.

function login(emailAddress: string, password: string) {
  ...
}

Before we implement it, let's define some errors this function could return.

import { defineError } from 'computer-says-no';

const InvalidCredentialsError = defineError(
  'INVALID_CREDENTIALS',
  'Invalid E-mail and Password combination'
);

const FieldRequiredError = defineError(
  'FIELD_REQUIRED',
  (fieldName: string) => `${fieldName} is required`)
);

Now we can write our login function. Notice we are returning the errors rather than throwing them, but if you prefer to throw errors that's cool too!

function login(emailAddress: string, password: string) {
  if (!emailAddress) {
    return new FieldRequiredError('Email');
  }

  if (!password) {
    return new FieldRequiredError('Password');
  }

  const userId = getMatchingUserId(emailAddress, password);
  if (!userId) {
    return new InvalidCredentialsError();
  }

  const authToken = getAuthTokenForUser(userId);
  return { authToken };
}

Note the return type of our login function will be (more or less):

| { code: 'FIELD_REQUIRED', message: string }
| { code: 'INVALID_CREDENTIALS', message: string }
| { authToken: string }

This makes it easy to check which result we got back when we call our login function (ignore the alert calls, this is just an example 😛).

import { isError } from 'computer-says-no';

function handleLoginSubmit() {
  const loginResult = login(emailAddress, password);

  if (isError(loginResult)) {
    alert(loginResult.message);
    return;
  }

  localStorage.setItem('authToken', loginResult.authToken);
  alert('Login successful');
}

Checking for specific error types

We can improve our login function validation if we set focus the field that has an issue.

Let's change our FieldRequiredError to include the name of the field.

const FieldRequiredError = defineError(
  'FIELD_REQUIRED',
  (fieldName: string) => ({
    message: `${fieldName} is required`,
    fieldName
  })
);

Now the FieldRequiredError will include a fieldName property. Let's update our login handler function.

function handleLoginSubmit() {
  const loginResult = login(emailAddress, password);

  if (FieldRequiredError.is(loginResult)) {
    const input = document.getElementById(loginResult.fieldName);
    input.focus();
  }

  if (isError(loginResult)) {
    alert(loginResult.message);
    return;
  }

  localStorage.setItem('authToken', loginResult.authToken);
  alert('Login successful');
}

But why?

Why not just create Error sub-classes and use the instanceof operator instead?

class FieldRequiredError extends Error {
    constructor(readonly fieldName: string) {
        super(`${fieldName} is required`);
    }
}

...

function handleLoginSubmit() {
  const loginResult = login(emailAddress, password);

  if (loginResult instanceof FieldRequiredError) {
    const input = document.getElementById(loginResult.fieldName);
    input.focus();
  }

  if (loginResult instanceof Error) {
    alert(loginResult.message);
    return;
  }

  localStorage.setItem('authToken', loginResult.authToken);
  alert('Login successful');
}

Well, the above is pretty elegant and requires no library. But sadly it doesn't scale if you're working on a monorepo and return errors from your API that you need to check for in your client. The instanceof operator will stop working.

This is where computer-says-no shines. Errors can be serialized to JSON and parsed back into plain old JS objects and all the type assertions will still work.

Using with GraphQL / Rest APIs

Errors instantiated by computer-says-no will include a property named csn. This is a signature the library includes that is essential for internally asserting that an error is a computer-says-no error.

You don't normally need to worry about it, except that this property must be included during any serialization. For example when resolving errors in GraphQL you must be sure GraphQL knows about and includes the csn property on the error type it resolves.

Contributing

Got an issue or a feature request? Log it.

Pull-requests are also welcome. 😸

changelog

Changelog

All notable changes to this project will be documented in this file. See standard-version for commit guidelines.

0.3.0 (2020-11-03)

⚠ BREAKING CHANGES

  • Renamed property to simply .

Features

  • once again rename the signature property to something graphql is happy with (64509b4)

0.2.0 (2020-11-03)

⚠ BREAKING CHANGES

  • Exposes csn property on error type, replaces $ property

Features

  • change error signature to csn and expose in error type (47f379a)

0.1.1 (2020-10-18)

0.1.0 (2020-10-18)

⚠ BREAKING CHANGES

  • Fields defined in error constructor will be automatically serialized and parsed on error creation now. This means fields like Date objects will become strings, and fields that are functions will be removed. This helps enforce the fact early on that errors should be serializable. The types already prevented users from passing in non-serializable fields, so this change will only effect users who are intentionally using any when defining error bodies to circumvent the type system.

Features

  • error body must now be serializable (bf476a3)

0.0.12 (2020-10-18)

0.0.11 (2020-10-18)

0.0.10 (2020-10-18)

0.0.9 (2020-10-18)

0.0.8 (2020-10-18)

0.0.7 (2020-10-17)

0.0.6 (2020-10-17)

0.0.5 (2020-10-13)

0.0.4 (2020-10-13)

Bug Fixes

  • correct spelling of error signature property (693a218)

0.0.3 (2020-10-12)

Bug Fixes

  • update ignore files for git and npm (dbadc7d)

0.0.2 (2020-10-12)

Bug Fixes

  • generate error class name based on error code (e55e402)

0.0.1 (2020-10-10)

Features

  • allow errors to be created using new keyword (a32f819)
  • initial code commit (5f430a5)
  • various improvements (d9992d3)