Next.js Discord

Discord Forum

Error handling in API routes

Unanswered
Chalcid wasp posted this in #help-forum
Open in Discord
Chalcid waspOP
if I have code like so, this won't typecheck when I need to return an error. What's the best practice? Using a type union instead of MyType?

export default function handler(req: NextApiRequest, res: NextApiResponse<MyType>) {
}

8 Replies

Asian black bear
Do you mean like throwing an exception in the function will somehow return the exception to the client to try/catch?
Chalcid waspOP
No returning an http error and a descriptive message
Something like res.status(400).json({message:”foobar”})
hmm, so return it
who's stopping you?
Western paper wasp
If MyType doesn’t include { message: "foobar" } you won’t be able to return that.

Maybe create another MyError type and use NextApiResponse<MyType | MyError>
Chalcid waspOP
Thanks @Western paper wasp that what I thought. I was wondering if this was the right approach or if I was missing knowledge/undersatnding of NextJS api and maybe there is a different way
Western paper wasp
nope you’re doing great