Lessons from opensource: Add a defensive type-safe error handler in your catch block
These lessons are picked from next.js/create-next-app open source code. In this article, you will see an unique error handler mechanims implemented in catch block.
isErrorLike function within catch block:
https://github.com/vercel/next.js/blob/canary/packages/create-next-app/create-app.ts#L180
I never wrote a function within catch block that was used within catch, that is an interesting pattern because you are defining the function within the proximity.
Imagine this isErrorLike function is at the top of your file, there is nothing wrong with that if you use isErrorLike in other places in the same file. But, if you don’t, just put the function within the catch block.
function isErrorLike(err: unknown): err is { message: string } {
return (
typeof err === 'object' &&
err !== null &&
typeof (err as { message?: unknown }).message === 'string'
)
}
The above function adds a type-safety to the error expected and that it should contain message property.
Subscribe to my newsletter to get more lessons from opensource.
DownloadError class
I looked at DownloadError and thought “This is cool, create-next-app has a class specific to DownloadError”.
How much efforts do you put it in to throw errors with class names aligned with the “try” block context? I usually just do throw new Error
. But the authors of create-next-app chose to be specific in naming the error by defining it as DownloadError class.
export class DownloadError extends Error {}
This class was part of create-app.ts file because this is where you download and extract a Github repo, my point is, this class is in the right file and is used only in 2 places across the codebase.
Conclusion:
You can add a function like isErrorLike
within catch block and in the proximity. You can declare it at the top of the file but I would do it only if I am using isErrorLike in other places. If not, I would just put it with in catch block.
Be specific with the thrown “Error” by defining a class name that extends Error in typescript like the “DownloadError”.
If you are looking to improve/learn frontend, checkout my website: https://tthroo.com/ where I teach project based tutorials.