GithubHelp home page GithubHelp logo

computer-says-no's Introduction

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. ๐Ÿ˜ธ

computer-says-no's People

Contributors

codeandcats avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.