Suppose I have the following async function
export async function someAsyncFunction() {
const result = await fetchData();
return result[0].id;
}
In the route I have
router.post(
'/some-path',
handleErrorAsync(async (req: Request, resp: Response, _err: Errback) => {
const data = await someAsyncFunction();
resp.json(data)
})
);
And I have error handling functionalities that do
interface ResponseError extends Error {
statusCode: number;
}
// 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);
}
}
export const handleErrorAsync = (func: Function) => (
req: Request,
res: Response,
next: NextFunction
) => {
func(req, res, next).catch((error: Error) => {
next(error);
});
};
So this works fine if for example fetchData
has an error response object, but this fails to print error objects when the error is a regular javascript error and instead it just prints {}
with 500 error.
For example in this line return result[0].id;
if the result is empty ([]
), then this would throw TypeError
, which will be caught by the handleError
middleware, but then the .json(err)
part will show only {}
Is there a way I can get both the servers errors (which are working correctly) and the internal server errors with that same middleware?