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

5.0.5 • Public • Published

@taktikal/error

Example usage

// ~/src/api/login.ts

const login = (username: string, password: string): AsyncResponse<{ token: string }> => {
  try {
    const { data: token } = await Axios.post("/login", { username, password });
    return [null, { token }];
  } catch (e) {
    return handleError(e, [
      {
        test: "User not found",
        message: "A user with this username does not exist",
        log: false,
      },
      {
        test: "Unauthorized",
        message: "Incorrect password",
        log: false,
      },
    ]);
  }
};
async function onSubmit() {
  const { username, password } = this.state;

  const [err, token] = await login(username, password);

  if (err) {
    showMessageToUser(err.message);
    return;
  }

  setAuthToken(token);
}

Install

npm i -S @taktikal/error

Setup

Client

// ~/config/configSentryBrowser.ts

import * as Sentry from "@sentry/browser";
import { setSentryInstance } from "@taktikal/error";
import { getPublicEnv } from "~/utils/env";

Sentry.init({
  dsn: getPublicEnv("SENTRY_DSN"),
  environment: getPublicEnv("SENTRY_ENV"),
});
setSentryInstance(Sentry);

Server

// ~/config/configSentryServer.ts

import * as Sentry from "@sentry/node";
import { setSentryInstance } from "@taktikal/error";
import { getPublicEnv } from "~/utils/env";

Sentry.init({
  dsn: getPublicEnv("SENTRY_DSN"),
  environment: getPublicEnv("SENTRY_ENV"),
});
setSentryInstance(Sentry);
// ~/server.ts

import "~/config/configSentryServer";

import express from "express";
import bodyParser from "body-parser";
import * as Sentry from "@sentry/node";
import { stripLongStrings } from "@taktikal/error";

const server = express();

server.use(bodyParser.json());

const sentryRequestHandler = Sentry.Handlers.requestHandler();
server.use((req, res, next) =>
  sentryRequestHandler({ ...req, body: stripLongStrings(req.body) } as express.Request, res, next),
);

// Middleware and routes go here

server.use(Sentry.Handlers.errorHandler());

// Server listen

Common config

// ~/config/configErrors.ts

import { config } from "@taktikal/error";

config({
  // Options go here
});

Config options

Option Type Default value Description
exposeDebugInformation boolean !IS_PROD_ENV If set to true, debug information will always be included when serializing the error.
logErrorsToSentry boolean IS_PROD_ENV If set to false, no errors will ever be logged to Sentry.
globalErrorCases ErrorCase[] [] All handled errors will be matched against these cases after local cases. Useful for error that can happen globally (e.g. network errors).
logBreadcrumbsToConsole boolean IS_DEV_ENV If set to true, breadcrumbs will be logged to the console.
logServerErrorsToConsole boolean IS_DEV_ENV If set to true, errors will be logged to the server console. The logged error is the LogError that is sent to Sentry instead of the StandardError.
logBrowserErrorsToConsole boolean IS_DEV_ENV If set to true, errors will be logged to the browser console. The logged error is the LogError that is sent to Sentry instead of the StandardError.
getExtraInfoFromRequest (req: Request) => any Data returned from this fn is set to the custom field of the stack.
siteUrl string "" This value is set to the siteUrl field of the stack.
errorHeaderValue string "" This value is used to determine whether or not to expose debug information to other services.

Error cases

Here are some common error cases.

Unwrap

If you want to use the unwrap syntax, you will need to add @taktikal/error/global to your types in tsconfig.json and import @taktikal/error/global at the root of your app.

// tsconfig.json
{
  "compilerOptions": {
    "types": [
      "node",
      "@taktikal/error/global"
      // ...
    ]
  }
}
// server.ts and/or _app.tsx

import "@taktikal/error/global";

Handling errors

The handleError function takes in the error, an optional options object, and an optional error case array.

// Only error
handleError(e);

// With a default error message
handleError(e, "Default error message");

// With an options object
handleError(e, { name: "Error name", message: "Default error message", extra: data });

// With error cases
handleError(e, [
  {
    test: "Unauthorized",
    message: "Innskráning tókst ekki",
    log: false,
  },
]);

// With options object and error cases
handleError(e, { name: "Error name", message: "Default error message", extra: data }, [
  {
    test: "Unauthorized",
    message: "Innskráning tókst ekki",
    log: false,
  },
]);

Functions

Synchronous functions that can fail should return a StandardResponse<T>. Async function should return AsyncResponse<T>.

type StandardResponse<T> = [null, T] | [StandardError, T];
type AsyncResponse<T> = Promise<StandardResponse<T>>;

The first item in the tuple is the error. The second item is the returned data.

I will refer to both StandardResponse<T> and AsyncResponse<T> as Response<T>. They are conceptually the same thing, except that AsyncResponse<T> wraps StandardResponse<T> in a Promise

Functions that return a Response<T> should never throw. Following that rule, consumers of functions that return Response<T> can use them without wrapping them in a try {} catch (e) {} block.

async function x() {
  const [err, data] = await getData();

  if (err) {
    // Handle the error
  }

  // Use the data
}

If there is unsafe code in the function (e.g. JSON.parse or a network call) the function should itself contain the try {} catch {} block.

import Axios from "axios";

const getData: AsyncFn<Data> = async () => {
  try {
    const { data } = await Axios.get("/data");
  } catch (e) {
    return handleError(e);
  }
};

Returning handleError(e) is the most basic way of handling an error. It will take care of parsing, formatting and logging the error.

StandardError

The handleError function returns [StandardError, null].

StandardError has two fields that you will use the majority of the time.

class StandardError {
  code: string;
  message: string;
}

Code

The code is used to match expected errors.

const [err] = handleError(e);

switch (err.code) {
  case "service_does_not_exist": {
    showCreateServiceSuggestionUI();
    break;
  }

  case "not_authenticated": {
    openLoginModal();
    break;
  }

  default: {
    setErrorMessage(err.message);
  }
}

If the code does not match any expected error, then showing err.message works as a nice fallback.

The code is "unknown" if no error case matched, though this case should NOT be matched directly.

Message

The message is a user-friendly error message that can be shown to the user.

const [err] = handleError(e);
setErrorMessage(err.message);

By default it is set to Eitthvað fór úrskeiðis.

Error cases

You can pass error cases to the handleError function:

const [err] = handleError(new Error("Login failed"), [
  {
    test: "Login failed",
    code: "login_failed"
    message: "The login attempt was unsuccessful, try again later!",
  },
]);

In this case, the first case would match. The err.code would be "login_failed" and err.message field would be "The login attempt was unsuccessful, try again later!".

The test field can be a string literal, a RegExp or a function that takes in the error itself or the Axios response payload.

A test function would pass the error itself by default, unless testBy is set to "data".

handleError(e, [
  {
    test: /^'Token' must be 20 characters in length. You entered [0-9]* characters.$/i,
    code: "token_length",
    message: "The token length is wrong.",
  },
  {
    test: (e: any) => e && e.response && e.response.data && e.response.data.field === 5,
    code: "generic_error",
    message: "Error message",
  },
  {
    testBy: "data",
    test: (data: Data) => data.field === 5,
    code: "generic_error",
    message: "Error message",
  },
]);

Error cases that test by data are only called if data is not null.

Log

Errors are logged to Sentry by default. You can decide to log or not to log certain errors by passing false to log.

handleError(new Error("Some error"), [
  {
    test: "Some error",
    code: "some_error",
    message: "Error message",
    log: false,
  },
]);

If log is not specified, the error is logged by default.

Unwrap

If you're doing multiple subsequent API calls, this can become a common pattern.

const handler: Handler = (req, res) => {
  const [customerErr, customer] = await getCustomer(req.query.token);

  if (customerErr) {
    customerErr.pipe(res);
    return;
  }

  const [signDocumentErr, document] = await signDocument(customer);

  if (signDocumentErr) {
    signDocumentErr.pipe(res);
    return;
  }

  const [sendDocumentErr] = await sendDocument(document);

  if (sendDocumentErr) {
    sendDocumentErr.pipe(res);
    return;
  }

  res.sendStatus(200);
};

OR

const fn = (): AsyncResponse<any> = (token: string) => {
  const [customerErr, customer] = await getCustomer(token);

  if (customerErr) {
    return [customerErr, null];
  }

  // ...
};

The majority of the code here is unnecessary boilerplate. You care about whether or not an error happened, but not necessarily which error since the functions themselves take care of defining the error message, logging it, etc.

The unwrap syntax helps with that:

const handler: Handler = (req, res) => {
  try {
    const customer = (await getCustomer(req.query.token)).unwrap();
    const document = (await signDocument(customer)).unwrap();
    (await sendDocument(document)).unwrap();

    res.sendStatus(200);
  } catch (e) {
    const [err] = handleError(e);
    err.pipe(res);
  }
};

Calling .unwrap() on a StandardResponse<T> will return T if there is no error. Otherwise it will throw the error.

Note that if you are using multiple unwrap statements in a single route or function, maybe the functions you are calling should not return Response<T> and rather just return T directly. The error cases can be moved to the bounding function.

Readme

Keywords

none

Package Sidebar

Install

npm i @taktikal/error

Weekly Downloads

0

Version

5.0.5

License

ISC

Unpacked Size

71.8 kB

Total Files

34

Last publish

Collaborators

  • alexharri
  • bjark