entropy
entropy8mo ago

Adding typing to ConvexError data field without casting everytime

Hello! I was using ConvexError and following the docs on adding custom data to the data field of ConvexError. The docs recommended casting for getting the correct typings, but I feel this would be a bit cumbersome. Is there any better way to do this?
3 Replies
erquhart
erquhart8mo ago
I don't know of a great alternative to casting here, but you could clean it up a bit by writing a generic function that takes the error and the error type you're expecting and returns the parsed and typed error.
entropy
entropyOP8mo ago
I see, yeah that's definitely the better approach thanks for the suggestion! I ended up doing this
interface CustomConvexError
extends ConvexError<{ message: string; code?: string }> {}

export function isCustomConvexError(
error: CustomConvexError | unknown
): error is CustomConvexError {
return (error as CustomConvexError).data.message !== undefined
}
interface CustomConvexError
extends ConvexError<{ message: string; code?: string }> {}

export function isCustomConvexError(
error: CustomConvexError | unknown
): error is CustomConvexError {
return (error as CustomConvexError).data.message !== undefined
}
so then I can just do this
if (isCustomConvexError(err)) {
return setError(err.data.message)
}
if (isCustomConvexError(err)) {
return setError(err.data.message)
}
Michal Srb
Michal Srb8mo ago
Yeah, that's the correct way. We had extending originally in the docs but were worried about folks getting confused. If you use a class instead of an interface you can actually throw your CustomConvexError on the backend - but beware that it can become a normal ConvexError when it propagates, so in try/catch you always need to use your isCustomConvexError helper.

Did you find this page helpful?