How to use http-errors - 10 common examples

To help you get started, we’ve selected a few http-errors examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github middyjs / middy / src / middlewares / __tests__ / httpErrorHandler.js View on Github external
test('It should be possible to pass a custom logger function', () => {
    const expectedError = new createError.UnprocessableEntity()
    const logger = jest.fn()

    const handler = middy((event, context, cb) => {
      throw expectedError
    })

    handler
      .use(httpErrorHandler({ logger }))

    // run the handler
    handler({}, {}, (_, response) => {
      expect(logger).toHaveBeenCalledWith(expectedError)
    })
  })
})
github flow-typed / flow-typed / definitions / npm / http-errors_v1.x.x / test_http-errors_v1.x.x.js View on Github external
import HttpErrors from 'http-errors';

const A: HttpErrors.HttpError = new HttpErrors.HttpError();
const B: HttpErrors.HttpError = HttpErrors();
const C: HttpErrors.HttpError = HttpErrors(200, 'foo', {});
// $ExpectError
const D: HttpErrors.HttpError = HttpErrors('500');
const E: HttpErrors.NotFound = new HttpErrors.NotFound();
const F: HttpErrors.HttpError = new HttpErrors.LengthRequired;
const G: HttpErrors.HttpError = new HttpErrors.HttpError('foo');

(F.expose: bool);
(F.message: string);
(F.status: number);
(F.statusCode: number);
github flow-typed / flow-typed / definitions / npm / http-errors_v1.x.x / test_http-errors_v1.x.x.js View on Github external
import HttpErrors from 'http-errors';

const A: HttpErrors.HttpError = new HttpErrors.HttpError();
const B: HttpErrors.HttpError = HttpErrors();
const C: HttpErrors.HttpError = HttpErrors(200, 'foo', {});
// $ExpectError
const D: HttpErrors.HttpError = HttpErrors('500');
const E: HttpErrors.NotFound = new HttpErrors.NotFound();
const F: HttpErrors.HttpError = new HttpErrors.LengthRequired;
const G: HttpErrors.HttpError = new HttpErrors.HttpError('foo');

(F.expose: bool);
(F.message: string);
(F.status: number);
(F.statusCode: number);
github graphql / express-graphql / src / parseBody.js View on Github external
}

  const rawBody = await readBody(req, typeInfo);
  // Use the correct body parser based on Content-Type header.
  switch (typeInfo.type) {
    case 'application/graphql':
      return { query: rawBody };
    case 'application/json':
      if (jsonObjRegex.test(rawBody)) {
        try {
          return JSON.parse(rawBody);
        } catch (error) {
          // Do nothing
        }
      }
      throw httpError(400, 'POST body sent invalid JSON.');
    case 'application/x-www-form-urlencoded':
      return querystring.parse(rawBody);
  }

  // If no Content-Type header matches, parse nothing.
  return {};
}
github windycom / git-deploy / src / lib / index.js View on Github external
const requestHandler = (checkRequest, parseRequest) => async (req, res, next) => {
	const args = checkRequest(req);
	if (!args) {
		next(new createError.NotFound());
		return;
	}
	let deployment = null;
	try {
		deployment = await parseRequest(req.body, ...args);
		if (!deployment) {
			// Don't treat this as error. This simply means: We ignore the request.
			res.status(201).end();
			return;
		}
		// Finish request first
		res.status(200).send('Deployment scheduled.');
	} catch (error) {
		console.error(error.message);
		res.status(error.statusCode || 500).send({
			error: error.message,
github woleet / woleet.id-server / server / src / api / routers / openid.ts View on Github external
router.get('/callback', async function (ctx) {
  const client = getClient();

  if (!client) {
    throw new ServiceUnavailable();
  }

  const oauth = ctx.cookies.get('oauth' + sessionSuffix);

  if (!oauth) {
    throw new BadRequest('Missing OAuth session');
  }

  ctx.cookies.set('oauth' + sessionSuffix, null);
  const oauthSession = lru.get(oauth);

  if (!oauthSession) {
    throw new BadRequest('Invalid OAuth session');
  }

  const { state, nonce } = oauthSession;

  let tokenSet;
  try {
    tokenSet = await client.authorizationCallback(
      getClientRedirectURL() /* TODO: check arg */,
      ctx.query,
github stephank / castling.club / src / front / inbox.ts View on Github external
} catch (err) {
      throw createError(
        400,
        `Activity document could not be loaded: ${err.message}`
      );
    }

    const activity = getActivity(store, parsed.id);
    if (!activity.type || !activity.actor) {
      throw createError(400, "Incomplete activity object");
    }

    // Verify the actor signature.
    const publicKey = await signing.verify(ctx, raw, store);
    if (publicKey.owner !== activity.actor) {
      throw createError(400, "Signature does not match actor");
    }

    // Verify the activity is from the actor's origin.
    if (originOf(activity.actor) !== origin) {
      throw createError(400, "Activity and actor origins don't match");
    }

    // Load the actor document.
    try {
      await store.load(activity.actor);
    } catch (err) {
      throw createError(
        400,
        `Actor document could not be loaded: ${err.message}`
      );
    }
github stephank / castling.club / src / front / inbox.ts View on Github external
ctx.body = null;
      return;
    }

    // We currently handle just 'Create'.
    if (activity.type === AS("Create")) {
      // The object MUST be inlined in the raw JSON, according to spec.
      // This also means it was already loaded into the store.
      if (typeof parsed.object !== "object") {
        throw createError(400, "Invalid object in 'Create' activity");
      }

      const object = getObject(store, activity.object!);
      if (object.type === AS("Note")) {
        if (object.attributedTo !== activity.actor) {
          throw createError(
            400,
            "Activity creates note not attributed to the actor"
          );
        }

        // Amend object with convenience props.
        const objectExt = {
          ...object,
          actor: actor,
          contentText: extractText(object.content || ""),
          mentions: new Set()
        };
        for (const tagId of object.tags) {
          // Assume these are also inlined in the JSON, and thus loaded.
          // If they're not, they'll simply not pass the type check.
          const tag = getTag(store, tagId);
github albertogasparin / react-starterkit / www / all / index.js View on Github external
async function all({ request, redirect, render, app }, next) {
  const routes = require('../../app/routes').default; // enable hot reload server-side
  let location = request.url;
  let redirectLocation, renderProps;

  // Use react-router match() to check if valid route
  try {
    [redirectLocation, renderProps] = await new Promise((res, rej) => {
      match({ routes, location }, (e, ...v) => (e ? rej(e) : res(v)));
    });
  } catch (err) {
    throw createError(500, err);
  }

  if (redirectLocation) {
    return redirect(redirectLocation.pathname + redirectLocation.search, '/');
  }

  if (!renderProps) {
    throw createError(404);
  }

  /**
   * If you are NOT intersted in server-side rendering
   * then replace following code with just:
   *
   * render(indexTpl);
   */
github stephank / castling.club / src / front / inbox.ts View on Github external
}

    // Load the activity document.
    const store = jsonld.createStore();
    try {
      await store.load(parsed);
    } catch (err) {
      throw createError(
        400,
        `Activity document could not be loaded: ${err.message}`
      );
    }

    const activity = getActivity(store, parsed.id);
    if (!activity.type || !activity.actor) {
      throw createError(400, "Incomplete activity object");
    }

    // Verify the actor signature.
    const publicKey = await signing.verify(ctx, raw, store);
    if (publicKey.owner !== activity.actor) {
      throw createError(400, "Signature does not match actor");
    }

    // Verify the activity is from the actor's origin.
    if (originOf(activity.actor) !== origin) {
      throw createError(400, "Activity and actor origins don't match");
    }

    // Load the actor document.
    try {
      await store.load(activity.actor);