-
Notifications
You must be signed in to change notification settings - Fork 0
Custom error classes #5
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
WalkthroughAdds a new @famiglio/errors library (BaseError, ValidationError, ConfigError, metadata schema, build config, LICENSE, README), wires it into the workspace via tsconfig references and package dependencies, and updates libs/core and libs/server-utils to throw ValidationError and simplify enum/schema usage. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor Caller
participant BaseError
participant Zod as ErrorMetadataSchema
Caller->>BaseError: new BaseError(message, metadata)
activate BaseError
BaseError->>Zod: safeParse(metadata)
alt valid
Zod-->>BaseError: parsed metadata
BaseError-->>Caller: returns Error instance (name, code, cause?, context?)
else invalid
Zod-->>BaseError: ZodError
BaseError-->>Caller: throws Error (metadata invalid) with cause
end
deactivate BaseError
sequenceDiagram
autonumber
actor App
participant Core as getNodeEnv
participant Server as getLogLevel
participant Errors as ValidationError
App->>Core: call getNodeEnv()
activate Core
alt valid
Core-->>App: returns validated NodeEnv
else invalid
Core->>Errors: create ValidationError(message, { provided, expected })
Core-->>App: throws ValidationError
end
deactivate Core
App->>Server: call getLogLevel(input)
activate Server
alt valid
Server-->>App: returns LogLevel
else invalid
Server->>Errors: create ValidationError(message, { provided, expected }, cause)
Server-->>App: throws ValidationError
end
deactivate Server
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
🧰 Additional context used🧬 Code graph analysis (1)libs/errors/src/base-error.ts (1)
🔇 Additional comments (1)
Comment |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (9)
libs/errors/LICENSE(1 hunks)libs/errors/package.json(1 hunks)libs/errors/src/base-error.ts(1 hunks)libs/errors/src/index.ts(1 hunks)libs/errors/src/schema.ts(1 hunks)libs/errors/tsconfig.json(1 hunks)libs/errors/tsconfig.lib.json(1 hunks)libs/errors/tsdown.config.ts(1 hunks)tsconfig.json(1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
libs/errors/src/schema.ts (1)
libs/errors/src/index.ts (2)
ErrorMetadataSchema(3-3)ErrorMetadata(2-2)
libs/errors/src/base-error.ts (2)
libs/errors/src/index.ts (3)
BaseError(1-1)ErrorMetadata(2-2)ErrorMetadataSchema(3-3)libs/errors/src/schema.ts (2)
ErrorMetadata(27-27)ErrorMetadataSchema(7-22)
🔇 Additional comments (8)
libs/errors/tsdown.config.ts (1)
1-13: LGTM!The tsdown configuration is correctly set up for building the errors library. The
dts: falsesetting is appropriate since type declarations are generated separately via thetsc -p tsconfig.lib.jsoncommand in the build target.libs/errors/LICENSE (1)
1-21: LGTM!Standard MIT License with appropriate copyright notice.
libs/errors/tsconfig.json (1)
1-10: LGTM!Standard TypeScript configuration for a library within a monorepo using project references.
tsconfig.json (1)
12-13: LGTM!Correctly adds the new errors library to the project references, integrating it into the monorepo build graph.
libs/errors/tsconfig.lib.json (1)
1-14: LGTM!The TypeScript library configuration is correctly set up with appropriate compiler options for a Node.js library.
libs/errors/src/schema.ts (2)
7-22: Well-designed error metadata schema.The use of
.strict()prevents accidental properties, and the requiredcodefield with minimum length validation ensures consistent error identification. The optionalcauseandcontextfields provide flexibility for error chaining and debugging context.
24-27: LGTM!Type inference from the Zod schema provides type safety while maintaining a single source of truth for the metadata structure.
libs/errors/src/index.ts (1)
1-3: LGTM!The exports are correctly structured with
.jsextensions for ESM compatibility and proper type-only export forErrorMetadata.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (1)
libs/server-utils/src/logger/get-log-level.ts (1)
19-20: Consider clarifying the error message.The message states "Invalid LOG_LEVEL environment variable," but since Line 15 uses
process.env.LOG_LEVEL ?? DEFAULT_LOG_LEVEL, it could be validating the default value when no environment variable is set.Apply this diff for more accurate messaging:
- throw new ValidationError( - 'Invalid LOG_LEVEL environment variable', + throw new ValidationError( + 'Invalid log level', result.error,
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (18)
libs/core/README.md(1 hunks)libs/core/package.json(2 hunks)libs/core/src/node-env.ts(1 hunks)libs/core/tsconfig.json(1 hunks)libs/core/tsconfig.lib.json(1 hunks)libs/errors/README.md(1 hunks)libs/errors/package.json(1 hunks)libs/errors/src/config-error.ts(1 hunks)libs/errors/src/index.ts(1 hunks)libs/errors/src/schema.ts(1 hunks)libs/errors/src/validation-error.ts(1 hunks)libs/server-utils/README.md(1 hunks)libs/server-utils/package.json(2 hunks)libs/server-utils/src/logger/get-log-level.ts(1 hunks)libs/server-utils/src/logger/log-level.ts(1 hunks)libs/server-utils/tsconfig.json(1 hunks)libs/server-utils/tsconfig.lib.json(1 hunks)package.json(1 hunks)
✅ Files skipped from review due to trivial changes (5)
- libs/server-utils/README.md
- libs/errors/README.md
- libs/core/tsconfig.json
- package.json
- libs/core/package.json
🚧 Files skipped from review as they are similar to previous changes (1)
- libs/errors/src/schema.ts
🧰 Additional context used
🧬 Code graph analysis (3)
libs/errors/src/config-error.ts (1)
libs/errors/src/index.ts (2)
ConfigError(2-2)BaseError(1-1)
libs/server-utils/src/logger/get-log-level.ts (1)
libs/server-utils/src/logger/log-level.ts (4)
LogLevel(28-28)DEFAULT_LOG_LEVEL(33-33)LogLevelSchema(18-18)LOG_LEVELS(6-13)
libs/server-utils/src/logger/log-level.ts (2)
libs/server-utils/src/index.ts (2)
LogLevelSchema(7-7)LOG_LEVELS(5-5)libs/server-utils/src/logger/index.ts (2)
LogLevelSchema(7-7)LOG_LEVELS(5-5)
🔇 Additional comments (14)
libs/server-utils/src/logger/log-level.ts (1)
18-18: LGTM! Cleaner enum construction.Directly using
LOG_LEVELSeliminates the intermediateLOG_LEVEL_VALUESarray, simplifying the code while maintaining the same functionality.libs/core/README.md (1)
10-61: LGTM! Comprehensive documentation.The Environment Management section clearly documents the
getNodeEnv()function, including available environments, usage examples, and error handling with structured payloads. The documentation aligns well with the new error handling approach.libs/server-utils/package.json (2)
50-51: LGTM! Dependencies correctly added.The new dependencies on
@famiglio/coreand@famiglio/errorsproperly wire the errors library into server-utils, supporting the structured error handling introduced in this PR.
64-68: LGTM! Appropriate NX tags.The NX tags correctly categorize this as a backend library within the shared scope.
libs/core/tsconfig.lib.json (1)
13-17: LGTM! TypeScript project reference correctly added.The reference to
../errors/tsconfig.lib.jsonproperly establishes the build dependency, ensuring the errors library is built before core.libs/server-utils/tsconfig.json (1)
9-11: LGTM! Project reference correctly added.The reference to
../errorsproperly integrates the errors library into the TypeScript project graph for server-utils.libs/server-utils/tsconfig.lib.json (1)
17-19: LGTM! Build dependency correctly established.The reference to
../errors/tsconfig.lib.jsonensures server-utils builds after errors, maintaining proper dependency order.libs/server-utils/src/logger/get-log-level.ts (1)
1-1: LGTM! Structured error handling is a solid improvement.The migration from generic
ErrortoValidationErrorwith a structured payload (provided value and expected options) significantly improves error diagnostics.Also applies to: 4-4, 19-26
libs/errors/src/validation-error.ts (1)
1-23: LGTM! Clear implementation with good documentation.The ValidationError class follows a clean pattern with structured metadata and appropriate error code. The implementation correctly extends BaseError and provides useful context for debugging validation failures.
libs/errors/src/config-error.ts (1)
1-23: LGTM! Consistent implementation with ValidationError.The ConfigError class follows the same pattern as ValidationError, which is good for consistency. While there's minor duplication between the two classes, having separate types improves clarity and type safety for different error scenarios.
libs/errors/src/index.ts (1)
1-5: LGTM! Clean and complete public API exports.The index file properly re-exports all necessary types and classes from the errors library. Good use of type-only export for ErrorMetadata on line 3.
libs/core/src/node-env.ts (3)
3-3: LGTM! Proper integration of the new error library.The import of ValidationError from @famiglio/errors aligns with the new error handling system introduced in this PR.
24-35: LGTM! Enhanced error handling with structured context.The use of ValidationError with structured context (provided and expected values) significantly improves debugging. The error message clearly communicates what went wrong and what values are valid.
5-10: No directNODE_ENVSproperty references detected
Search forNODE_ENVS.<ENV>yielded no matches; switching to an array is safe.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
♻️ Duplicate comments (1)
libs/errors/src/base-error.ts (1)
38-38: Verify thatErrorMetadataInputrequirescodeat compile-time.The past review comment suggested requiring
codeat the type level to prevent runtime validation failures. The current signature usesErrorMetadataInput, which should enforcecodeas required since it's derived from the Zod schema wherecodeis mandatory. However, it's worth verifying that TypeScript correctly flags missingcodefields.Run the following script to verify the type behavior:
#!/bin/bash # Description: Check if any BaseError instantiations omit the required 'code' field # Search for BaseError constructor calls across the codebase rg -n --type=ts -A 3 'new BaseError\(' # Search for subclass constructors that might pass incomplete metadata rg -n --type=ts -A 5 'super\(.+,\s*\{' libs/errors/src/
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (6)
libs/core/src/node-env.ts(1 hunks)libs/errors/package.json(1 hunks)libs/errors/src/base-error.ts(1 hunks)libs/errors/src/schema.ts(1 hunks)libs/errors/src/validation-error.ts(1 hunks)libs/server-utils/src/logger/get-log-level.ts(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- libs/server-utils/src/logger/get-log-level.ts
- libs/errors/package.json
🧰 Additional context used
🧬 Code graph analysis (3)
libs/errors/src/validation-error.ts (2)
libs/errors/src/index.ts (2)
ValidationError(5-5)BaseError(1-1)libs/errors/src/base-error.ts (1)
BaseError(11-99)
libs/errors/src/schema.ts (1)
libs/errors/src/index.ts (2)
ErrorMetadataSchema(4-4)ErrorMetadata(3-3)
libs/errors/src/base-error.ts (1)
libs/errors/src/schema.ts (3)
ErrorMetadataInput(28-28)ErrorMetadataOutput(29-29)ErrorMetadataSchema(7-22)
🪛 GitHub Actions: Check and Fix Workspace
libs/errors/src/base-error.ts
[error] 2-2: ESLint: 'ZodError' is defined but never used. Allowed unused vars must match /^_/u @typescript-eslint/no-unused-vars
🪛 GitHub Check: workspace-fixes
libs/errors/src/base-error.ts
[warning] 46-46:
Unknown word: "proprietà"
[warning] 46-46:
Unknown word: "Assegna"
[failure] 5-5:
'ErrorMetadata' is defined but never used. Allowed unused vars must match /^_/u
[failure] 2-2:
'ZodError' is defined but never used. Allowed unused vars must match /^_/u
🔇 Additional comments (5)
libs/errors/src/schema.ts (1)
1-29: LGTM! Well-structured error metadata schema.The schema correctly enforces a required non-empty
codefield while allowing flexiblecauseandcontextfields. The use of.strict()prevents accidental typos in property names, and the exported type aliases provide proper TypeScript integration.libs/errors/src/validation-error.ts (1)
1-23: LGTM! Clean and focused error specialization.The
ValidationErrorclass properly extendsBaseErrorwith a consistent error code. The constructor signature provides flexibility by makingcauseandcontextoptional, which is appropriate for different validation scenarios.libs/errors/src/base-error.ts (1)
55-98: LGTM! Robust validation and serialization.The
validateMetadatamethod appropriately usessafeParseand provides clear error messages when validation fails, wrapping the Zod error as the cause. ThetoJSONmethod correctly normalizes the cause and provides a comprehensive serialization for logging and debugging.libs/core/src/node-env.ts (2)
3-12: LGTM! Clean integration of the new error library.The import of
ValidationErrorand the refactoring ofNODE_ENVSto an array withas constproperly integrates with the new@famiglio/errorspackage. The schema definition usingz.enum(NODE_ENVS)is the correct Zod pattern.
23-39: LGTM! Improved error handling with structured context.The updated implementation properly throws
ValidationErrorwith useful context information. Theprovidedandexpectedfields in the context object will help developers quickly identify and fix NODE_ENV issues.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
libs/core/src/node-env.ts(1 hunks)libs/errors/src/base-error.ts(1 hunks)libs/errors/src/schema.ts(1 hunks)libs/server-utils/src/logger/get-log-level.ts(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- libs/errors/src/schema.ts
- libs/server-utils/src/logger/get-log-level.ts
🧰 Additional context used
🧬 Code graph analysis (2)
libs/core/src/node-env.ts (1)
libs/core/src/index.ts (4)
NODE_ENVS(3-3)NodeEnvSchema(5-5)NodeEnvEnum(4-4)getNodeEnv(2-2)
libs/errors/src/base-error.ts (1)
libs/errors/src/schema.ts (3)
ErrorMetadataInput(28-28)ErrorMetadataOutput(29-29)ErrorMetadataSchema(7-22)
🔇 Additional comments (3)
libs/core/src/node-env.ts (3)
3-3: Good addition of ValidationError import.The import aligns with the PR objective of using custom error classes from the new @famiglio/errors library.
5-10: Good simplification of NODE_ENVS structure.Changing from an object to an array is cleaner and works well with
z.enum(). This maintains the same public API while reducing complexity.
28-31: ValidationError usage
Constructor signature supports (message, cause, context); current usage is correct.
Summary by CodeRabbit
New Features
Documentation
Chores