Skip to content

Extract error codes from CosmosDB storage to centralized errorHelper with tokenized helplinks#773

Merged
cleemullins merged 18 commits intomainfrom
copilot/extract-error-codes-cosmosdb
Nov 19, 2025
Merged

Extract error codes from CosmosDB storage to centralized errorHelper with tokenized helplinks#773
cleemullins merged 18 commits intomainfrom
copilot/extract-error-codes-cosmosdb

Conversation

Copy link
Copy Markdown
Contributor

Copilot AI commented Nov 14, 2025

Plan: Extract Error Codes from CosmosDB to errorHelper.ts ✅

  • Create errorHelper.ts file modeled after the C# ErrorHelper class
    • Define AgentErrorDefinition interface (moved to agents-activity)
    • Define AgentError interface for proper TypeScript typing
    • Define error codes starting from -100000 range (20 errors defined)
    • Include error text with formatting strings using named parameters
    • Include help URLs with tokenized {errorCode} placeholder
    • Format exception messages as [CODE] - [message] - [helplink]
  • Extract all error messages from cosmosDbPartitionedStorage.ts (11 errors found)
  • Extract error message from cosmosDbKeyEscape.ts (1 error found)
  • Update cosmosDbPartitionedStorage.ts to use errorHelper
  • Update cosmosDbKeyEscape.ts to use errorHelper
  • Update index.ts to export errorHelper
  • Build and validate changes
  • Run linting checks
  • Run security scan (CodeQL - no issues found)
  • Manual verification and testing
  • Add unit tests for errorHelper
  • Address code review feedback
  • Move ExceptionHelper to agents-activity package for cross-package reuse
  • Refactor AgentErrorDefinition from class to interface
  • Refactor ErrorHelper class to Errors const object
  • Change message formatting to use named parameters instead of array indices
  • Add AgentError interface to eliminate TypeScript warnings
  • Refactor helplinks to use {errorCode} token to eliminate duplication

Summary

Successfully extracted all error codes from the agents-hosting-storage-cosmos package into a centralized error definitions file, following the C# implementation pattern, and added comprehensive unit tests. Moved ExceptionHelper and AgentErrorDefinition to the agents-activity package to enable reuse across all packages in the SDK. Simplified error definitions from a class to a const object, implemented named parameter formatting for better readability and fault tolerance, added proper TypeScript typing to eliminate warnings when accessing custom error properties, formatted exception messages to include error codes and help links, and refactored helplinks to use a tokenized format that eliminates error code duplication.

Changes Made:

1. Created agents-activity/src/exceptionHelper.ts with:

  • AgentErrorDefinition interface - represents error definitions with code, description, and help link
  • AgentError interface - extends Error with custom properties (code, helpLink, innerException) for proper TypeScript typing
  • ExceptionHelper class - generates exceptions with error codes and help links
  • Uses named parameters object for message formatting: params?: { [key: string]: string }
  • Returns properly typed errors: T & AgentError
  • Replaces {errorCode} token in helplinks with actual error code at runtime
  • Formats exception messages as: [CODE] - [message] - [helplink] (e.g., [-100000] - CosmosDbPartitionedStorageOptions is required. - https://aka.ms/M365AgentsErrorCodes/#-100000)
  • Exported from agents-activity for cross-package reuse

2. Created agents-hosting-storage-cosmos/src/errorHelper.ts with:

  • Errors const object - contains 20 error definitions (codes -100000 to -100019)
  • All errors defined as object literals conforming to AgentErrorDefinition interface
  • Error messages use named placeholders (e.g., {containerId}, {databaseId}, {keySuffix}) instead of indexed placeholders ({0}, {1})
  • All helplinks use tokenized format: https://aka.ms/M365AgentsErrorCodes/#{errorCode} instead of hardcoded error codes
  • Error codes defined only once in the code field, eliminating duplication and maintenance issues
  • Simple structure: export const Errors: { [key: string]: AgentErrorDefinition } = { ... }

3. Updated cosmosDbPartitionedStorage.ts:

  • Replaced all hardcoded error strings with Errors definitions
  • Refactored to use ExceptionHelper.generateException() consistently throughout
  • All calls use named parameter objects: { keySuffix: 'value' } instead of positional arguments
  • Removed inefficient throwInformativeError method with runtime lookup
  • All error exceptions now include error codes and help links in the message
  • Fixed 404 error handling (now treated as non-errors for read/delete operations)
  • Imports ExceptionHelper from @microsoft/agents-activity
  • Uses Errors const object

4. Updated cosmosDbKeyEscape.ts:

  • Replaced hardcoded error string with Errors definition
  • Imports ExceptionHelper from @microsoft/agents-activity
  • Uses Errors const object

5. Updated package exports:

  • agents-activity/src/index.ts - exports AgentError, AgentErrorDefinition and ExceptionHelper
  • agents-hosting-storage-cosmos/src/index.ts - exports Errors and re-exports AgentError, AgentErrorDefinition, ExceptionHelper from agents-activity

6. Created comprehensive unit tests:

  • agents-activity/test/exceptionHelper.test.ts (11 tests) - tests for AgentErrorDefinition interface and ExceptionHelper class
  • Tests use proper AgentError typing - no as any or @ts-expect-error comments needed
  • Tests validate formatted message structure: [CODE] - [message] - [helplink]
  • Tests validate {errorCode} token replacement in helplinks
  • agents-hosting-storage-cosmos/test/errorHelper.test.ts (7 tests) - tests for Errors object definitions (uniqueness, format, range)
  • Tests validate tokenized helplink format
  • All 18 tests pass ✅

7. Code Review Improvements:

  • Fixed semicolon consistency in errorHelper.ts
  • Improved inner exception handling (stored as custom property instead of constructor parameter)
  • Fixed variable check that always evaluated to true (removed redundant && check)
  • Refactored all error throwing to use ExceptionHelper consistently
  • Removed inefficient runtime error code lookup in throwInformativeError
  • Eliminated throwInformativeError method entirely in favor of ExceptionHelper
  • Fixed type conversion for err parameter in checkForNestingError
  • Simplified ErrorHelper class to Errors const object for better usability
  • Implemented named parameter formatting for better readability and fault tolerance
  • Added AgentError interface to eliminate TypeScript warnings on custom error properties
  • Formatted exception messages to include error code and help link in standardized format
  • Refactored helplinks to use {errorCode} token to eliminate error code duplication

Named Parameters Benefits:

  • More readable: { containerId: 'myContainer', partitionKeyPath: '/path' } vs 'myContainer', '/path'
  • More fault-tolerant: parameter order doesn't matter
  • Self-documenting: parameter names are explicit in the code

TypeScript Benefits:

  • No TypeScript warnings: Custom properties are properly typed via AgentError interface
  • Better IntelliSense: IDE provides autocomplete for code, helpLink, and innerException
  • Type safety: Compile-time checking of custom error properties
  • No type assertions needed: Tests access properties directly without as any or @ts-expect-error

Exception Message Format Benefits:

  • Error code in message: Users can immediately identify the error code from the message
  • Help link in message: Direct access to documentation without accessing properties
  • Standardized format: [CODE] - [message] - [helplink] pattern is consistent across all exceptions
  • Easy to parse: Clear delimiters for logging and monitoring systems

Tokenized Helplink Benefits:

  • Single source of truth: Error code appears only once in the error definition (in the code field)
  • Eliminates duplication: Helplink is generated from error code automatically using {errorCode} token
  • Reduces maintenance: Changing error code automatically updates helplink without manual synchronization
  • Prevents errors: Cannot have mismatched codes between code field and helplink URL
  • Flexible: Works with or without the token (pass-through for custom URLs that don't contain {errorCode})

Error Code Range:

  • Base: -100000
  • Range: -100000 to -100019 (20 errors total)

Architecture:

  • agents-activity: Contains reusable ExceptionHelper, AgentError interface, and AgentErrorDefinition interface for use across all packages
  • agents-hosting-storage-cosmos: Contains package-specific Errors const object with 20 CosmosDB error definitions using tokenized helplinks

Verification:

✅ Build successful
✅ Linting passed
✅ Manual testing verified
✅ Security scan (CodeQL) - no issues found
✅ Package exports validated
18 unit tests added - all passing (11 in agents-activity, 7 in agents-hosting-storage-cosmos)
Code review feedback addressed
ExceptionHelper moved to agents-activity for cross-package reuse
Error definitions simplified from class to const object
Message formatting uses named parameters for better readability and fault tolerance
No TypeScript warnings on custom error properties
Exception messages formatted with error code and help link
Helplinks use {errorCode} token to eliminate duplication

All changes follow the C# pattern from the Agents-for-net repository.

Original prompt

This section details on the original issue you should resolve

<issue_title>Extracting Error Codes from CosmosDB</issue_title>
<issue_description>In the package "agents-hosting-storage-cosmos" all instances of exceptions thrown need to have their string values extracted to a file called "errorHelper.js".

This file needs to be modeled after the C# Version of this class, found here:
https://github.com/microsoft/Agents-for-net/blob/main/src/libraries/Core/Microsoft.Agents.Authentication/Errors/ErrorHelper.cs

Each defined error should have:

  • The error text, including any formatting string(s).
  • An error code. The Javascript error range for these errors start at -100000 and may go all the way down to -10100.
  • The URL the user can follow to learn more. That URL Looks like: https://aka.ms/M365AgentsErrorCodes/#-40000. The deeplink hasthag is the error number.

Any "helper" class that needs to be defined can be added to this file. </issue_description>

Comments on the Issue (you are @copilot in this section)


💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.

Co-authored-by: cleemullins <1165321+cleemullins@users.noreply.github.com>
Copilot AI changed the title [WIP] Extract error codes from CosmosDB to errorHelper.js Extract error codes from CosmosDB storage to centralized errorHelper Nov 14, 2025
Copilot AI requested a review from cleemullins November 14, 2025 20:07
@cleemullins
Copy link
Copy Markdown
Collaborator

@copilot Add in a set of simple unit tests.

Co-authored-by: cleemullins <1165321+cleemullins@users.noreply.github.com>
Copy link
Copy Markdown
Contributor Author

Copilot AI commented Nov 14, 2025

@copilot Add in a set of simple unit tests.

Added comprehensive unit tests for errorHelper in commit 1f89bf7. The test suite includes 21 tests covering:

  • AgentErrorDefinition class functionality
  • ErrorHelper error definitions validation (uniqueness, format, range)
  • ExceptionHelper exception generation
  • Message formatting with parameters
  • Integration tests for various error scenarios

All tests pass successfully.

@cleemullins cleemullins marked this pull request as ready for review November 14, 2025 21:02
Copilot AI review requested due to automatic review settings November 14, 2025 21:02
@cleemullins cleemullins requested a review from benbrown November 14, 2025 21:03
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR successfully extracts all error strings from the CosmosDB storage package into a centralized errorHelper.ts module, following the C# pattern from Agents-for-net. The implementation introduces structured error definitions with error codes (-100000 to -100019), descriptions, and help URLs.

Key changes:

  • New errorHelper.ts with AgentErrorDefinition, ErrorHelper (20 error definitions), and ExceptionHelper classes
  • Updated error handling in cosmosDbPartitionedStorage.ts and cosmosDbKeyEscape.ts to use centralized error definitions
  • Comprehensive test suite with 21 unit tests covering all error helper functionality

Reviewed Changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 8 comments.

Show a summary per file
File Description
src/errorHelper.ts New centralized error helper with error definitions, codes, and help URLs
src/cosmosDbPartitionedStorage.ts Replaced hardcoded error strings with ErrorHelper definitions; enhanced throwInformativeError with error codes
src/cosmosDbKeyEscape.ts Updated to use ErrorHelper for missing key parameter error
src/index.ts Exported error helper classes for external consumption
test/errorHelper.test.ts Comprehensive unit tests for all error helper functionality
tsconfig.json Excluded test directory from compilation output

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread packages/agents-hosting-storage-cosmos/src/errorHelper.ts Outdated
Comment thread packages/agents-hosting-storage-cosmos/src/errorHelper.ts Outdated
Comment thread packages/agents-hosting-storage-cosmos/src/cosmosDbPartitionedStorage.ts Outdated
Comment thread packages/agents-hosting-storage-cosmos/src/cosmosDbPartitionedStorage.ts Outdated
Comment thread packages/agents-hosting-storage-cosmos/src/cosmosDbPartitionedStorage.ts Outdated
Comment thread packages/agents-hosting-storage-cosmos/src/cosmosDbPartitionedStorage.ts Outdated
Comment thread packages/agents-hosting-storage-cosmos/src/errorHelper.ts Outdated
Comment thread packages/agents-hosting-storage-cosmos/src/errorHelper.ts Outdated
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
cleemullins and others added 4 commits November 14, 2025 14:50
…Storage.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
…Storage.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
…nner exception handling

Co-authored-by: cleemullins <1165321+cleemullins@users.noreply.github.com>
Copilot AI changed the title Extract error codes from CosmosDB storage to centralized errorHelper and move ExceptionHelper to agents-activity Extract error codes from CosmosDB storage to centralized errorHelper with named parameters Nov 18, 2025
@cleemullins cleemullins requested a review from benbrown November 18, 2025 22:45
Copy link
Copy Markdown
Contributor

@benbrown benbrown left a comment

Choose a reason for hiding this comment

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

Why are we changing the tsconfig file?

Comment thread packages/agents-activity/tsconfig.json Outdated
Comment thread packages/agents-hosting-storage-cosmos/tsconfig.json Outdated
Comment thread packages/agents-activity/test/exceptionHelper.test.ts Outdated
…rror properties

Co-authored-by: cleemullins <1165321+cleemullins@users.noreply.github.com>
Copilot AI changed the title Extract error codes from CosmosDB storage to centralized errorHelper with named parameters Extract error codes from CosmosDB storage to centralized errorHelper with typed error interface Nov 19, 2025
@cleemullins
Copy link
Copy Markdown
Collaborator

@copilot - the generated exception message needs to be in the format: [CODE] - [message] - [helplink]. Update the ExceptionHelper class to generate the right error message.

Co-authored-by: cleemullins <1165321+cleemullins@users.noreply.github.com>
Copy link
Copy Markdown
Contributor Author

Copilot AI commented Nov 19, 2025

@copilot - the generated exception message needs to be in the format: [CODE] - [message] - [helplink]. Update the ExceptionHelper class to generate the right error message.

Updated in commit 97bfdee. Exception messages are now formatted as [CODE] - [message] - [helplink].

Example output:

[-100000] - CosmosDbPartitionedStorageOptions is required. - https://aka.ms/M365AgentsErrorCodes/#-100000

All 16 tests updated and passing with the new message format.

Copilot AI changed the title Extract error codes from CosmosDB storage to centralized errorHelper with typed error interface Extract error codes from CosmosDB storage to centralized errorHelper with formatted error messages Nov 19, 2025
@cleemullins cleemullins requested a review from benbrown November 19, 2025 18:21
@cleemullins
Copy link
Copy Markdown
Collaborator

@copilot, refactor the Errors class and the ExceptionHelper class, so that the error number only needs to be found in a single spot in the Error definition. Having the error number it in two spots is error prone and will make maintenance harder.

Tokenize the helplink to look like this:

helplink: 'https://aka.ms/M365AgentsErrorCodes/#{errorCode}'

and have the ExceptionHelper class replace the errorCode with the actual error number.

This should end up looking like this:

helplink: 'https://aka.ms/M365AgentsErrorCodes/#0100000'

If the "errorCode" isn't present in the help link, just leave the link alone and pass it through directly.

For example, in this code block the error code is defined, and it's duplicated again in the helplink.

 MissingCosmosDbStorageOptions: {
    code: -100000,
    description: 'CosmosDbPartitionedStorageOptions is required.',
    helplink: 'https://aka.ms/M365AgentsErrorCodes/#-100000'
  },

This should look like:

 MissingCosmosDbStorageOptions: {
    code: -100000,
    description: 'CosmosDbPartitionedStorageOptions is required.',
    helplink: 'https://aka.ms/M365AgentsErrorCodes/#{errorCode}'
  },

Co-authored-by: cleemullins <1165321+cleemullins@users.noreply.github.com>
Copy link
Copy Markdown
Contributor Author

Copilot AI commented Nov 19, 2025

@copilot, refactor the Errors class and the ExceptionHelper class, so that the error number only needs to be found in a single spot in the Error definition. Having the error number it in two spots is ...

Completed in commit df76e61. Refactored to use tokenized {errorCode} in helplinks to eliminate duplication:

Changes:

  • All error definitions now use helplink: 'https://aka.ms/M365AgentsErrorCodes/#{errorCode}' instead of hardcoded error codes
  • ExceptionHelper.generateException() replaces {errorCode} token with actual error code at runtime
  • Error code is now defined in only one place (the code field)
  • If {errorCode} token is not present, helplink is passed through unchanged

Example:

MissingCosmosDbStorageOptions: {
  code: -100000,
  description: 'CosmosDbPartitionedStorageOptions is required.',
  helplink: 'https://aka.ms/M365AgentsErrorCodes/#{errorCode}'
}

Generates exception with helplink: https://aka.ms/M365AgentsErrorCodes/#-100000

All 18 tests pass, including new tests verifying token replacement behavior.

Copilot AI changed the title Extract error codes from CosmosDB storage to centralized errorHelper with formatted error messages Extract error codes from CosmosDB storage to centralized errorHelper with tokenized helplinks Nov 19, 2025
@cleemullins cleemullins merged commit 63cf9e3 into main Nov 19, 2025
7 checks passed
@cleemullins cleemullins deleted the copilot/extract-error-codes-cosmosdb branch November 19, 2025 21:40
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.

Extracting Error Codes from CosmosDB

4 participants