Skip to content

Instantly share code, notes, and snippets.

@najibla
Last active November 26, 2020 12:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save najibla/24a2838adc9221cb5585ed34eb9ce926 to your computer and use it in GitHub Desktop.
Save najibla/24a2838adc9221cb5585ed34eb9ce926 to your computer and use it in GitHub Desktop.

With Express, I am doing the following

export async function fetchData(token: any, body: any) {
  const result = await fetch(
    `${config.apiUrl}/${config.projectKey}/my-request`,
    {
      method: 'POST',
      headers: {
        Authorization: token,
      },
      body: JSON.stringify(body),
    }
  );

  const json = await result.json();
  if (!result.ok) {
    throw {
      statusCode: result.status,
      ...json
    };
  }
  return json;
}

and in the route I do

router.post(
  '/some-path',
  handleErrorAsync(async (req: Request, resp: Response, _err: Errback) => {
    const data = await fetchData(req.get('authorization'), req.body);
    resp.json(data)
  })
);

And I have an error handling module that does

interface ResponseError extends Error {
  statusCode: number;
}

// async functions errors handler to avoid using try catch for every async route

export const handleErrorAsync = (func: Function) => (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  func(req, res, next).catch((error: Error) => {
    next(error);
  });
};

// middleware to respond with an error when error caught
export function handleError(
  err: ResponseError,
  _req: Request,
  resp: Response,
  _next: NextFunction
) {
  if (err) {
    resp.status(err.statusCode || 500).json(err);
  }
}

And of course I add to the router

router.use(handleError);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment