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);