mailtrap-nodejs icon indicating copy to clipboard operation
mailtrap-nodejs copied to clipboard

Fix axios error parsing

Open narekhovhannisyan opened this issue 2 months ago β€’ 1 comments

Motivation

The axios logger was failing to properly extract error messages from API responses, resulting in unhelpful error messages like [object Object] instead of meaningful root cause information. This made debugging difficult for developers using the SDK, as they couldn't identify what went wrong with their API requests.

The logger only handled basic error formats (single error strings, arrays of strings, and objects with name/base properties) but failed to handle:

  • Arrays of error objects with nested field-specific errors
  • Objects with direct field-specific errors (e.g., { "email": ["is invalid"] })
  • Arrays of objects with direct base field (no identifier)

Additionally, the code used for...of loops which violated linting rules requiring array methods instead.

Changes

  • Enhanced error message extraction - Now properly handles all error response formats:

    • Arrays of error objects with nested errors (e.g., contact imports validation)
    • Objects with field-specific errors (e.g., { "email": ["is invalid"] })
    • Arrays of objects with direct base field
    • Arrays of strings
    • Single error strings
    • Objects with name/base properties (legacy format)
  • Refactored to use array methods - Replaced all for...of loops with functional array methods (map, filter, reduce) to comply with linting rules

  • Extracted simple, focused functions - Broke down complex logic into smaller, testable functions:

    • formatFieldError - Formats a single field error message
    • extractFieldErrors - Extracts all field errors from an object
    • getErrorIdentifier - Gets email/id identifier from error object
    • extractNestedErrors - Extracts errors from nested "errors" property
    • extractDirectErrors - Extracts errors directly from object properties
    • formatErrorMessage - Formats a single error object into message string
  • Updated tests - Fixed test expectations to match the improved error message extraction behavior

How to test

  • [ ] Run existing test suite: npm test -- src/__tests__/lib/axios-logger.test.ts src/__tests__/lib/api/resources/ContactImports.test.ts src/__tests__/lib/mailtrap-client.test.ts

  • [ ] Test with real API calls that trigger various error formats:

    • Contact imports with invalid emails (array of error objects)
    • Contact creation with invalid email (object with field errors)
    • Contact list creation with empty name (object with name/base errors)
    • Sending API with missing fields (array of strings)
    • Non-existent resource requests (single error string)
  • [ ] Verify error messages are human-readable and show root cause (no more [object Object])

  • [ ] Verify linting passes: npm run lint

  • [ ] Verify build succeeds: npm run build

Summary by CodeRabbit

  • Bug Fixes

    • Improved API error-message formatting β€” arrays, nested field errors and identifiers are now consolidated into clearer, user-facing messages.
  • Tests

    • Added and updated extensive unit tests to validate error-message extraction/formatting across many API error shapes and edge cases, ensuring consistent, readable error text.

narekhovhannisyan avatar Nov 11 '25 14:11 narekhovhannisyan

[!WARNING]

Rate limit exceeded

@narekhovhannisyan has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 8 minutes and 30 seconds before requesting another review.

βŒ› How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 8f35cc8ae0826fe27c1cc48fc277d7ff2e7b62a4 and d54fe04c4a140048889e1d30daabbed050dfda3a.

πŸ“’ Files selected for processing (1)
  • src/lib/axios-logger.ts (1 hunks)

Walkthrough

Centralizes and refactors Axios error handling into helper functions that extract and format error messages from varied response shapes, updates handleSendingError to use the new builder, and adjusts/extends unit tests to validate the new message formats and edge cases.

Changes

Cohort / File(s) Change Summary
Axios error formatting refactor
src/lib/axios-logger.ts
Introduces helper functions (e.g., formatFieldError, extractFieldErrors, getErrorIdentifier, extractNestedErrors, extractDirectErrors, formatErrorMessage, extractMessagesFromErrorObjects, extractErrorMessage, buildErrorMessage) and centralizes error-message construction; handleSendingError now delegates to buildErrorMessage and throws MailtrapError with the composed message and original error as cause.
Unit tests for axios-logger
src/__tests__/lib/axios-logger.test.ts
Adds comprehensive tests covering single-string errors, arrays of strings, arrays of error objects, nested errors, field maps, identifier-only errors, plain-text responses, fallbacks for null/invalid response data, and preservation of the original Axios error as cause.
Test expectation updates
src/__tests__/lib/api/resources/ContactImports.test.ts, src/__tests__/lib/api/resources/ContactExports.test.ts
Updates expected error messages to match new composed formatting (e.g., formatted messages for arrays of validation objects) and aligns tests to fallback behavior for unrecognized shapes (e.g., "Request failed with status code 422"). Comments adjusted/removed accordingly.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant Client
    participant Axios as AxiosRequest
    participant Logger as handleSendingError
    participant Builder as buildErrorMessage
    participant Extractor as extractErrorMessage
    participant Formatter as formatErrorMessage
    participant MailtrapError as MailtrapError

    Client->>Axios: perform request
    Axios-->>Client: throws AxiosError (response.data)
    Client->>Logger: handleSendingError(error)
    Logger->>Builder: buildErrorMessage(error)
    Builder->>Extractor: extractErrorMessage(response.data, default)
    note right of Extractor `#f0f4ff`: Inspect `data.error` / `data.errors` / nested shapes
    alt errors is array of objects
        Extractor->>Formatter: extractMessagesFromErrorObjects(...)
        Formatter-->>Extractor: concatenated message
    else errors is field map
        Extractor->>Formatter: extractFieldErrors(...)
        Formatter-->>Extractor: joined field messages
    else plain string / unknown
        Extractor-->>Builder: return default or `error.message`
    end
    Extractor-->>Builder: composed message
    Builder-->>Logger: final message
    Logger->>MailtrapError: throw MailtrapError(message) with cause = original error
    MailtrapError-->>Client: propagated MailtrapError

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • Files/areas to review carefully:
    • src/lib/axios-logger.ts β€” ordering and correctness of multi-shape extraction/formatting logic.
    • src/__tests__/lib/axios-logger.test.ts β€” coverage, expected message strings, and cause preservation.
    • Updated expectations in ContactImports.test.ts and ContactExports.test.ts β€” ensure alignment with other callers of handleSendingError.

Possibly related PRs

  • mailtrap/mailtrap-nodejs#95 β€” Related to axios-logger error extraction changes impacting ContactImports tests.
  • mailtrap/mailtrap-nodejs#98 β€” Related changes affecting error-message formatting used by ContactExports tests.

Suggested reviewers

  • VladimirTaytor
  • mklocek

Poem

🐰 I hopped through messy JSON and strings,

I stitched field errors into tidy things,
IDs and messages now sing in a row,
Tests nod when the composed messages show,
A carrot of clarity β€” hop, fix, and go! πŸ₯•

Pre-merge checks and finishing touches

βœ… Passed checks (3 passed)
Check name Status Explanation
Title check βœ… Passed The title 'Fix axios error parsing' clearly and concisely summarizes the main changeβ€”improving axios error message extraction from API responses.
Description check βœ… Passed The description includes all key sections: Motivation (explains the problem and impact), Changes (lists all enhancements with details), and How to test (provides specific test commands and scenarios).
Docstring Coverage βœ… Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❀️ Share

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

coderabbitai[bot] avatar Nov 11 '25 14:11 coderabbitai[bot]