Skip to content

feat: add error handling and log warning for ormconfig loading failures - #11871

Merged
pkuczynski merged 2 commits into
typeorm:masterfrom
Cprakhar:feat/warning-ormconfig-load
Dec 26, 2025
Merged

pkuczynski merged 2 commits into
typeorm:masterfrom
Cprakhar:feat/warning-ormconfig-load

Conversation

@Cprakhar

Copy link
Copy Markdown
Collaborator

Description of change

This PR adds warning messages when ormconfig configuration files fail to load, addressing issue #6960.

Problem:
Previously, when TypeORM's ConnectionOptionsReader encountered errors loading ormconfig files (e.g., syntax errors in ormconfig.js, invalid JSON in ormconfig.json, or module resolution failures), these errors were silently swallowed. This led to confusing debugging sessions where developers spent hours trying to figure out why their configuration wasn't working, with no indication that the file loading had failed.

Solution:
Added try-catch blocks around file loading operations in ConnectionOptionsReader.load() that:

  • Catch errors when loading .env, .js, .mjs, .cjs, .ts, .mts, .cts, and .json configuration files
  • Log clear warning messages using PlatformTools.logWarn() with:
    • The specific file path that failed to load
    • The actual error message from the failure
  • Allow execution to continue gracefully (existing behavior preserved)

Example output:

Warning: Could not load ormconfig file at /path/to/ormconfig.js
Cannot find module 'some-missing-dependency'

Verification:

  • Added comprehensive unit tests in test/unit/connection-options-reader/connection-options-reader.test.ts
  • Tests verify that warnings are logged when configuration files fail to load
  • All existing tests continue to pass
  • Manually tested with malformed configuration files to confirm warning messages appear

Benefits:

  • Developers immediately see when configuration loading fails
  • Error messages include the specific file path and error details
  • Significantly reduces debugging time for configuration issues
  • No breaking changes - existing behavior preserved

Pull-Request Checklist

  • Code is up-to-date with the master branch
  • This pull request links relevant issues as Fixes #6960
  • There are new or updated tests validating the change (tests/**.test.ts)
  • Documentation has been updated to reflect this change (docs/docs/**.md)

Fixes #6960

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis ✅

6960 - PR Code Verified

Compliant requirements:

  • Warning messages are logged when ormconfig file fails to load
  • Warnings include the specific file path and error message details
  • Implementation is in ConnectionOptionsReader.ts (the reusable component)
  • Execution continues gracefully after logging warnings (existing behavior preserved)

Requires further human verification:

  • Verify that the warning messages appear correctly in actual CLI usage scenarios (e.g., when running migration:create command)
  • Confirm that the warning format and verbosity are appropriate for end users
  • Test with various types of configuration file errors (syntax errors, missing dependencies, invalid JSON, etc.)
⏱️ Estimated effort to review: 2 🔵🔵⚪⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Test Coverage Gap

The test only covers malformed JS files. Consider adding tests for other file formats mentioned in the implementation (.json, .env, .mjs, .cjs, .ts, .mts, .cts) to ensure warnings are logged correctly for all supported configuration file types.

it("should log warning when ormconfig file fails to load", async () => {
    // Create a malformed JS config file
    await fs.writeFile(
        "./temp/configs/malformed-config.js",
        "module.exports = { invalid syntax here",
    )

    // Spy on logWarn
    const originalLogWarn = PlatformTools.logWarn
    let warnCalled = false
    let warnMessage = ""
    PlatformTools.logWarn = (...args: any[]) => {
        warnCalled = true
        warnMessage = args.join(" ")
    }

    try {
        const reader = new ConnectionOptionsReader({
            root: "./temp",
            configName: "configs/malformed-config",
        })
        await reader.all()
    } catch (err: any) {
        expect(err.message).to.include("No connection options were found")
    } finally {
        PlatformTools.logWarn = originalLogWarn
        await fs.unlink("./temp/configs/malformed-config.js")
    }

    expect(warnCalled).to.be.true
    expect(warnMessage).to.include("Could not load ormconfig file")
})
Silent Failure

When configuration file loading fails, the code logs a warning but continues execution. If connectionOptions remains undefined, the method returns an empty array. This might lead to confusing behavior where users see a warning but the application continues without proper configuration, potentially causing issues downstream.

try {
    const [importOrRequireResult, moduleSystem] =
        await importOrRequireFile(configFile)
    const configModule = await importOrRequireResult

    if (
        moduleSystem === "esm" ||
        (configModule &&
            "__esModule" in configModule &&
            "default" in configModule)
    ) {
        connectionOptions = configModule.default
    } else {
        connectionOptions = configModule
    }
} catch (err) {
    PlatformTools.logWarn(
        `Warning: Could not load ormconfig file at ${configFile}`,
        err instanceof Error ? err.message : String(err),
    )
}

@pkg-pr-new

pkg-pr-new Bot commented Dec 25, 2025

Copy link
Copy Markdown
  • typeorm-sql-js-example

    npm i https://pkg.pr.new/typeorm/typeorm@11871
    

commit: c037353

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Prevent resource leaks in tests

To prevent resource leaks, refactor the test by wrapping the setup and execution
logic within a try...finally block to ensure cleanup code is always executed.

test/unit/connection-options-reader/connection-options-reader.test.ts [115-146]

 it("should log warning when ormconfig file fails to load", async () => {
-    // Create a malformed JS config file
-    await fs.writeFile(
-        "./temp/configs/malformed-config.js",
-        "module.exports = { invalid syntax here",
-    )
-
-    // Spy on logWarn
+    const configPath = "./temp/configs/malformed-config.js"
     const originalLogWarn = PlatformTools.logWarn
     let warnCalled = false
     let warnMessage = ""
-    PlatformTools.logWarn = (...args: any[]) => {
-        warnCalled = true
-        warnMessage = args.join(" ")
-    }
 
     try {
-        const reader = new ConnectionOptionsReader({
-            root: "./temp",
-            configName: "configs/malformed-config",
-        })
-        await reader.all()
-    } catch (err: any) {
-        expect(err.message).to.include("No connection options were found")
+        // Create a malformed JS config file
+        await fs.writeFile(
+            configPath,
+            "module.exports = { invalid syntax here",
+        )
+
+        // Spy on logWarn
+        PlatformTools.logWarn = (...args: any[]) => {
+            warnCalled = true
+            warnMessage = args.join(" ")
+        }
+
+        try {
+            const reader = new ConnectionOptionsReader({
+                root: "./temp",
+                configName: "configs/malformed-config",
+            })
+            await reader.all()
+        } catch (err: any) {
+            expect(err.message).to.include("No connection options were found")
+        }
+
+        expect(warnCalled).to.be.true
+        expect(warnMessage).to.include("Could not load ormconfig file")
     } finally {
         PlatformTools.logWarn = originalLogWarn
-        await fs.unlink("./temp/configs/malformed-config.js")
+        await fs.unlink(configPath).catch(() => {
+            /* ignore */
+        })
     }
-
-    expect(warnCalled).to.be.true
-    expect(warnMessage).to.include("Could not load ormconfig file")
 })
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies a potential resource leak in the test case where cleanup might not run if setup fails, and proposes a valid structural improvement to make the test more robust.

Low
  • More

@gioboa gioboa left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks great to me 👏 @Cprakhar

@pkuczynski pkuczynski added this to the 1.0 milestone Dec 26, 2025
@pkuczynski
pkuczynski merged commit f2547e1 into typeorm:master Dec 26, 2025
@Cprakhar
Cprakhar deleted the feat/warning-ormconfig-load branch January 7, 2026 15:00
mgohin pushed a commit to mgohin/typeorm that referenced this pull request Jan 15, 2026
kranners pushed a commit to kranners/typeorm that referenced this pull request Mar 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

Add Warning When ormconfig Fails to Load

3 participants