npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@openfinance/http-errors

v1.5.1

Published

A set of extensions to the standard Error class that add features that make it easy to convert thrown errors into detailed HTTP responses.

Downloads

5

Readme

Http Errors

NOTE: This library is now hosted on github packages at https://github.com/openfinanceio/ts-http-errors. For the latest updates, please use the package @openfinanceio/ts-http-errors and point npm to github package repo (github guide).

This is a small library that presents a set of pre-configured errors that correspond to some common HTTP status codes, such as 400, 401, 403, 404, 500, etc....

The idea is that you can throw these like normal errors in your code, but then use them to fine-tune your actual HTTP response in a global handler function. For example, using express:

import * as express from "express";
import * as errors from "http-errors";
import { authenticate } from "./Authnz";

const app = express();

// Normal endpoint
app.get("/my/endpoint", function(req, res, next) {
  try {
    if (!req.headers("Authorization")) {
      throw new errors.Unauthorized("You must pass a standard Authorization header to use this endpoint", "MissingAuthHeader");
    }

    // May throw errors.Forbidden
    authenticate(req.headers("Authorization"));

    return res.status(200).send({data:"Yay!"});
  } catch (e) {
    next(e);
  }
});

// Global handler, handling errors for all endpoints
app.use(function(e: Error, req, res, next) {
  // If it's not already an HttpError, convert it into an InternalServerError (500)
  if (!errors.isHttpError(e)) {
    e = errors.InternalServerError.fromError(e);
  }

  // This happens to be JSON:API structure, but you could use the data however you'd like
  return res.status(e.status).send({
    errors: [
      {
        status: e.status,
        code: e.code!,
        title: e.title,
        detail: e.message
      }
    ]
  });
});

API

The best way to understand the API for these errors is to simply look at the definitions file, which is fairly small. However, for ease of reference, below is an overview:

isHttpError()

This is a simple function that offers typeguarding for errors. For any catch block, you can simply pass in the error object you receive, and if it's not an HttpError, you can convert it to one using the static fromError() method available on all errors in the library.

HttpError

This is the (abstract) base class for all errors in this library. All errors have the following properties, which are defined in this base class:

  • readonly tag: "HttpError" = "HttpError" -- Always HttpError so you can easily tell whether or not you're dealing with an HttpError.
  • readonly name: string; -- An error ID which is usually statically defined. For example, a "Bad Request" might be defined with this property set to BadRequest, such that you can always determine what type of error you're dealing with at runtime.
  • readonly status: HttpStatusCode; -- any of the (finite) list of valid HTTP numeric status codes. This is usually defined statically in the specific error definition, so you don't have to set it yourself.
  • errno?: number; -- Part of the NodeJS.ErrnoException interface.
  • code?: string; -- A useful code indicating what specific error this is (e.g., IncorrectEmail,
  • readonly subcode?: string; -- A secondary code to further specify the error (e.g., IncorrectFormat, MiddleNameRequired, etc....)
  • path?: string; -- The path through the data where the error occurred (e.g., data.attributes.legalName)
  • syscall?: string; -- Part of the NodeJS.ErrnoException interface.
  • stack?: string; -- Part of the NodeJS.ErrnoException interface.
  • obstructions: Array<ObstructionInterface<{[param: string]: any}>>; -- This error's array of obstructions (see Obstructions below).

HttpError itself is an abstract class. You'll actually be using descendent classes when throwing errors (see Basic Errors below). These descendent errors are distinguishable at runtime (and in the context of discriminated unions) via the name attribute, which will usually be the same as the constructor, but is defined statically in the descendant class definitions.

The code, and subcode properties allow for further differentiation. code is a property from the NodeJS.ErrnoException interface and often used by native errors. Therefore, it is usually avoided in HttpErrors. subcode, on the other hand, is settable via the optional second constructor parameter on every HttpError and may be used to very specifically describe the error.

For example, you might define and use a new InvalidEmail Error like so:

class InvalidEmailError extends BadRequest {
  code = "InvalidEmail"
}

// ...

throw new InvalidEmailError("Your email must be in standard format", "IncorrectFormat");

In the above example, you can easily throw an error with a lot of data attached to it by default, then add specificity ("IncorrectFormat") in context.

fromError

HttpError defines a static method, fromError which takes any Error object and converts it to an HttpError of the given type. This is most often used to turn native Errors into InternalServerErrors like so:

try {
  woops this is gonna throw
} catch (e) {
  if (!isHttpError(e)) {
    e = InternalServerError.fromError(e);
  }

  // Now we know it's an HttpError. Format it and return a response
  // ...
}

Obstructions

The concept of obstructions is specific to the HttpErrors world. An obstruction is defined as follows:

interface ObstructionInterface<ParamSet extends {[param: string]: unknown}> {
  code: string;
  text: string;
  params?: ParamSet;
}

These are meant to be light-weight and data-dense packets that allow you to communicate to consumers about multiple issues that are preventing a given request from completing successfully.

Imagine you're registering a new user. Using the BadRequest error with obstructions, you can easily stop execution and send back a 400 with useful information from anywhere in your code:

const body = req.body;
if (!body) {
  throw new BadRequest("Missing request body. Did you send it?");
}
if (!body.user) {
  throw new BadRequest("Missing incoming user object. Did you send it?");
}

const obstructions: Array<ObstructionInterface<GenericParams>> = [];

if (!body.user.name) {
  obstructions.push({
    code: "NoUserName",
    text: "You must send a user name to register."
  });
}

if (!body.user.email) {
  obstructions.push({
    code: "NoEmail",
    text: "You must send an email for the user you're registering."
  });
} else {
  if (!validateEmail(body.user.email, ourEmailRegex) {
    obstructions.push({
      code: "InvalidEmail",
      text: "Your email doesn't appear to be in valid format.",

      // Note that we can provide data so consumers can be more detailed about
      // how they display the errors
      params: {
        email: body.user.email,
        pattern: ourEmailRegex
      }
    });
  }
}

if (!body.user.password) {
  obstructions.push({
    code: "NoPassword",
    text: "You haven't provided a password."
  });
} else {
  if (!body.user.passwordConfirmation) {
    obstructions.push({
      code: "NoPasswordConf",
      text: "You haven't provided a password confirmation."
    });
  } else {
    if (body.user.password !== body.user.passwordConfirmation) {
      obstructions.push({
        code: "PasswordConfMismatch",
        text: "Your password confirmation doesn't match the password you entered."
      });
    }
  }
}

if (obstructions.length > 0) {
  const e = new BadRequest("There were problems registering your user.");
  e.obstructions = obstructions;
  throw e;
}

// Now we know it's safe. Continue processing here....