Skip to content

Conversation

@dcdavidev
Copy link
Contributor

@dcdavidev dcdavidev commented Oct 12, 2025

Summary by CodeRabbit

  • New Features

    • Standardized error library (BaseError, ValidationError, ConfigError) with machine-readable codes, optional cause/context, and JSON serialization.
    • Environment and log-level helpers now throw structured validation errors for invalid inputs.
  • Documentation

    • Added README and MIT license for the new errors library; updated core and server-utils docs to reference the unified error system.
  • Chores

    • Added errors package, package manifests, build configs, and TypeScript project references across affected libs.

@coderabbitai
Copy link

coderabbitai bot commented Oct 12, 2025

Walkthrough

Adds 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

Cohort / File(s) Summary of Changes
Licensing
libs/errors/LICENSE
Added MIT License for the errors library.
Errors package manifest
libs/errors/package.json
New package.json for @famiglio/errors with exports, files, deps/devDeps, and NX build/watch targets.
Errors: implementation & API
libs/errors/src/base-error.ts, libs/errors/src/config-error.ts, libs/errors/src/validation-error.ts, libs/errors/src/schema.ts, libs/errors/src/index.ts
New BaseError (Zod-validated metadata, prototype fix, toJSON), ConfigError and ValidationError subclasses, ErrorMetadataSchema and types, and index re-exports.
Errors: build config & tsconfig
libs/errors/tsdown.config.ts, libs/errors/tsconfig.json, libs/errors/tsconfig.lib.json
Added tsdown config and TypeScript project/lib configs for building the errors package.
Workspace TS refs
tsconfig.json, libs/core/tsconfig.json, libs/core/tsconfig.lib.json, libs/server-utils/tsconfig.json, libs/server-utils/tsconfig.lib.json
Added project references to libs/errors in workspace and dependent libs (updates TypeScript project graph).
Core: env handling
libs/core/src/node-env.ts, libs/core/README.md, libs/core/package.json
NODE_ENVS converted to a string tuple; NodeEnvSchema now built from it; getNodeEnv now throws ValidationError with structured payload; README and deps updated to include @famiglio/errors and zod.
Server-utils: logging
libs/server-utils/src/logger/get-log-level.ts, libs/server-utils/src/logger/log-level.ts, libs/server-utils/README.md, libs/server-utils/package.json
getLogLevel now throws ValidationError (with cause/context) on invalid values; LogLevelSchema simplified to use LOG_LEVELS directly; README and package.json NX tags/deps updated to include @famiglio/errors and @famiglio/core.
Root & workspace package updates
package.json
Added devDependency on @famiglio/errors in root package.json.
Documentation for errors lib
libs/errors/README.md
New README describing BaseError, subclasses, usage, serialization, examples, and license.

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
Loading
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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • Refactor of the server-utils lib #4 — Adjusts server-utils logging utilities and enum construction; directly related to server-utils changes that now consume @famiglio/errors.

Poem

I hop through code with gentle paws,
I guard each field and tidy laws.
Zod at my side, I stamp the cause,
Errors neat in tidy clause.
Logs hum true — a rabbit's applause. 🐇✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Description Check ⚠️ Warning The pull request lacks any description and does not follow the repository’s required template sections for purpose, related issues, checklist, or additional context. Please add a pull request description that follows the template by explaining the purpose of this PR and the problems it solves, listing any related issues, confirming the checklist items, and including any additional notes or context.
✅ Passed checks (2 passed)
Check name Status Explanation
Title Check ✅ Passed The title “Custom error classes” succinctly highlights the introduction of new error classes such as BaseError, ConfigError, and ValidationError, which represent the core addition of this pull request, and is specific enough to reflect the main change without including unnecessary details.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/errors-lib

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f088a8a and 480431a.

📒 Files selected for processing (1)
  • libs/errors/src/base-error.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
libs/errors/src/base-error.ts (1)
libs/errors/src/schema.ts (3)
  • ErrorMetadataInput (28-28)
  • ErrorMetadataOutput (29-29)
  • ErrorMetadataSchema (7-22)
🔇 Additional comments (1)
libs/errors/src/base-error.ts (1)

1-98: LGTM! Excellent implementation of BaseError with all previous issues resolved.

The implementation is solid and production-ready:

  • All past review comments have been addressed (required code type, unused imports removed, JSDoc formatting fixed)
  • Proper use of ErrorMetadataInput type ensures compile-time and runtime alignment with the Zod schema
  • The prototype chain fix (line 48) and new.target.name (line 39) ensure correct inheritance and class naming for subclasses
  • Runtime validation with clear error messages provides good developer experience
  • The toJSON() method offers comprehensive serialization for structured logging and telemetry

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a 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

📥 Commits

Reviewing files that changed from the base of the PR and between d3d2642 and 2f53d41.

⛔ Files ignored due to path filters (1)
  • package-lock.json is 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: false setting is appropriate since type declarations are generated separately via the tsc -p tsconfig.lib.json command 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 required code field with minimum length validation ensures consistent error identification. The optional cause and context fields 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 .js extensions for ESM compatibility and proper type-only export for ErrorMetadata.

Copy link

@coderabbitai coderabbitai bot left a 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

📥 Commits

Reviewing files that changed from the base of the PR and between 2f53d41 and afe3e52.

⛔ Files ignored due to path filters (1)
  • package-lock.json is 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_LEVELS eliminates the intermediate LOG_LEVEL_VALUES array, 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/core and @famiglio/errors properly 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.json properly 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 ../errors properly 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.json ensures 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 Error to ValidationError with 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 direct NODE_ENVS property references detected
Search for NODE_ENVS.<ENV> yielded no matches; switching to an array is safe.

Copy link

@coderabbitai coderabbitai bot left a 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 that ErrorMetadataInput requires code at compile-time.

The past review comment suggested requiring code at the type level to prevent runtime validation failures. The current signature uses ErrorMetadataInput, which should enforce code as required since it's derived from the Zod schema where code is mandatory. However, it's worth verifying that TypeScript correctly flags missing code fields.

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

📥 Commits

Reviewing files that changed from the base of the PR and between afe3e52 and 3ed4b28.

⛔ Files ignored due to path filters (1)
  • package-lock.json is 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 code field while allowing flexible cause and context fields. 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 ValidationError class properly extends BaseError with a consistent error code. The constructor signature provides flexibility by making cause and context optional, which is appropriate for different validation scenarios.

libs/errors/src/base-error.ts (1)

55-98: LGTM! Robust validation and serialization.

The validateMetadata method appropriately uses safeParse and provides clear error messages when validation fails, wrapping the Zod error as the cause. The toJSON method 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 ValidationError and the refactoring of NODE_ENVS to an array with as const properly integrates with the new @famiglio/errors package. The schema definition using z.enum(NODE_ENVS) is the correct Zod pattern.


23-39: LGTM! Improved error handling with structured context.

The updated implementation properly throws ValidationError with useful context information. The provided and expected fields in the context object will help developers quickly identify and fix NODE_ENV issues.

Copy link

@coderabbitai coderabbitai bot left a 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

📥 Commits

Reviewing files that changed from the base of the PR and between 3ed4b28 and f088a8a.

📒 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.

@dcdavidev dcdavidev merged commit c06dea8 into main Oct 12, 2025
5 checks passed
@dcdavidev dcdavidev deleted the feat/errors-lib branch October 12, 2025 16:43
@coderabbitai coderabbitai bot mentioned this pull request Oct 12, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants