In this article, we analyze how a file named error.ts is used across the shadcn/ui code base.
utils/errors.ts
error.ts
contains 12 variables:
export const MISSING_DIR_OR_EMPTY_PROJECT = "1"
export const EXISTING_CONFIG = "2"
export const MISSING_CONFIG = "3"
export const FAILED_CONFIG_READ = "4"
export const TAILWIND_NOT_CONFIGURED = "5"
export const IMPORT_ALIAS_MISSING = "6"
export const UNSUPPORTED_FRAMEWORK = "7"
export const COMPONENT_URL_NOT_FOUND = "8"
export const COMPONENT_URL_UNAUTHORIZED = "9"
export const COMPONENT_URL_FORBIDDEN = "10"
export const COMPONENT_URL_BAD_REQUEST = "11"
export const COMPONENT_URL_INTERNAL_SERVER_ERROR = "12"
These are descriptive and explain the kind of error being handled, for example, MISSING_DIR_OR_EMPTY_PROJECT is likely used in a scenario where there is missing directory or empty project.
Is there any special meaning to these variable values? they are just numbers assigned as strings. It makes more sense once we understand how these variables are used.
Usage in preflight-init.ts:
If you open this preflight-init.ts, you will find the below code snippet in there.
// Ensure target directory exists.
// Check for empty project. We assume if no package.json exists, the project is empty.
if (
!fs.existsSync(options.cwd) ||
!fs.existsSync(path.resolve(options.cwd, "package.json"))
) {
errors[ERRORS.MISSING_DIR_OR_EMPTY_PROJECT] = true
return {
errors,
projectInfo: null,
}
}
Pay attention to this errors[ERRORS.MISSING_DIR_OR_EMPTY_PROJECT]=true
, here errors is an object. What’s the value of MISSING_DIR_OR_EMPTY_PROJECT? it was “1” as explained earlier.
This mean errors object would look like below:
{
"1": true
}
This is fine, but how’s this error object used and where? The answer is in init.ts.
errors object in init.ts
At line 91, in init.ts, you will find the below if
block.
if (preflight.errors[ERRORS.MISSING_DIR_OR_EMPTY_PROJECT]) {
const { projectPath } = await createProject(options)
if (!projectPath) {
process.exit(1)
}
options.cwd = projectPath
options.isNewProject = true
}
if this check was something like preflight.error[“1”], your next thought immediately is what’s this mysterious value here. This means, these constants in error.ts are used to improve code readability
About me:
Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.
I am open to work on an interesting project. Send me an email at ramu.narasinga@gmail.com
My Github - https://github.com/ramu-narasinga
My website - https://ramunarasinga.com
My Youtube channel - https://www.youtube.com/@thinkthroo
Learning platform - https://thinkthroo.com
Codebase Architecture - https://app.thinkthroo.com/architecture
Best practices - https://app.thinkthroo.com/best-practices
Production-grade projects - https://app.thinkthroo.com/production-grade-projects
Top comments (0)