Having issue with error types in TypeScript
async function getUserById(req: Request, res: Response) {
const userId = parseInt(req.params.id);
try {
const user = await prisma.user.findUniqueOrThrow({
where: {
id: userId,
},
});
res.status(200).json(user);
} catch (error: Prisma.PrismaClientKnownRequestError) {
res.status(404).json({ message: error.meta });
}
}
problem: TSError: ⨯ Unable to compile TypeScript:
controllers/userController/userController.ts:36:19 - error TS1196: Catch clause variable type annotation must be 'any' or 'unknown' if specified.
the error returned is of type Prisma.PrismaClientKnownRequestError
i dont quite understand the problem2 Replies
catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError)
res.status(404).json({ message: error.meta?.cause });
res.status(404).json(error);
}
so far this is the way i am handeling it
i know returning error.meta.cause is not a good idea but my main focus is how to access specific attributes inside an error objectit happens because the
catch
can't have any type besides any
or unknown