Skip to content

Comments

Handle outlook watch error better#729

Merged
elie222 merged 1 commit intomainfrom
chore/outlook-watch-logging
Aug 29, 2025
Merged

Handle outlook watch error better#729
elie222 merged 1 commit intomainfrom
chore/outlook-watch-logging

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Aug 29, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Improved reliability of email watch setup to prevent silent failures.
    • Clearer error messages surfaced when a watch cannot be established.
    • Enhanced logging with contextual details for faster troubleshooting.
  • Refactor

    • Standardized response format for watch operations with explicit success and error details.
    • Consistent handling of success/failure paths across related endpoints.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 29, 2025

Walkthrough

Introduces a structured result for watchEmails, updates controller to return success/error with expirationDate or message, and refactors watch route handlers to consume the new result, add contextual logging on failures, and propagate error details.

Changes

Cohort / File(s) Summary of Changes
Watch controller
apps/web/app/api/watch/controller.ts
Changes return type to a discriminated union with success/error; on success returns { success: true, expirationDate }; adds explicit handling for falsy provider results; enhances catch block logging and returns { success: false, error }; removes legacy null returns.
Watch route handlers
apps/web/app/api/watch/route.ts, apps/web/app/api/watch/all/route.ts
Refactors to use const result = await watchEmails(...); checks result.success; on success uses result.expirationDate; on failure logs provider/email context and error, and records errorDetails where applicable.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Client
  participant Route as HTTP Route (/api/watch[/**])
  participant Controller as watchEmails Controller
  participant Provider as Email Provider

  Client->>Route: POST watch request
  Route->>Controller: watchEmails({ emailAccountId, provider })
  Controller->>Provider: provider.watchEmails(...)
  alt Provider returns result
    Provider-->>Controller: { expirationDate }
    Controller-->>Route: { success: true, expirationDate }
    Route-->>Client: 200 OK with expirationDate
  else Provider returns falsy or throws
    Provider-->>Controller: null / throws Error
    Controller-->>Route: { success: false, error }
    Note over Route: Log error with context (provider/email/emailAccountId)
    Route-->>Client: 4xx/5xx with errorDetails
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • Fix comments on Outlook PR #554 — Also modifies watchEmails return type and adjusts route handling/logging for the same controller and route files, indicating overlapping refactors.

Poem

A rabbit watched the inbox stream,
Ticking dates like a punctual dream.
Success hops in with time to spare,
Errors squeak—we log with care.
Now routes and controllers speak as one—
Burrows tidy, work well done. 🐇✉️

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch chore/outlook-watch-logging

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbit in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbit in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbit gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbit read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbit help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbit ignore or @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbit summary or @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbit or @coderabbitai anywhere in the PR title to generate the title automatically.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@claude
Copy link

claude bot commented Aug 29, 2025

Claude finished @elie222's task —— View job


PR Review - Handle Outlook Watch Error Better

I'll review this PR for code quality, potential bugs, performance, security, and test coverage.

Todo List:

  • Read repository guidelines (CLAUDE.md) - Not found
  • Review the 3 modified files
  • Analyze git diff to understand exact changes
  • Provide comprehensive feedback on code quality, bugs, performance, security, and test coverage

📋 Summary

This PR improves error handling in the Outlook watch functionality by:

  1. Changing watchEmails to return a structured result object instead of throwing exceptions
  2. Adding explicit error logging when watch setup fails
  3. Providing more detailed error information in API responses

✅ Positive Changes

Improved Error Handling

  • The new return type Promise<{ success: true; expirationDate: Date } | { success: false; error: string }> makes error states explicit and prevents silent failures
  • Better error propagation from controller.ts to calling functions
  • More detailed error logging throughout the chain

Enhanced Observability

  • Added structured logging with error details in route.ts:69-73 and all/route.ts:108-114
  • Error messages now include provider and account context for easier debugging

🔍 Code Quality Issues

1. Inconsistent Error Logging (controller.ts:51-60)

logger.error("Error watching inbox", {
  emailAccountId,
  providerName: provider.name,
  error, // ← Original error object
});
captureException(error);
return { success: false, error: errorMessage }; // ← String version

The logger receives the full error object while the return value gets a string. Consider logging the string version too for consistency.

2. Redundant Success Logging (controller.ts:17-20 & controller.ts:26-31)
The function logs "Watching emails" twice - once at the start and once on success. The second log provides more detail, so consider removing the first one or making them more distinct.

3. Missing Type Safety (route.ts:78)

errorDetails: result.error,

TypeScript knows result.error exists here, but the response interface should explicitly define errorDetails as optional.

🐛 Potential Issues

1. Database Consistency Risk (controller.ts:33-39)
If the database update fails after a successful provider.watchEmails(), the provider will have a watch subscription but the database won't reflect it. Consider wrapping in a transaction or adding rollback logic.

2. Error Message Exposure (route.ts:78, route.ts:91)
Internal error messages from providers are exposed directly to API consumers. Consider sanitizing error messages to prevent information disclosure:

errorDetails: sanitizeErrorMessage(result.error)

🔒 Security Considerations

Low Risk: Error messages could potentially expose internal implementation details. The current approach logs full errors internally (good) but also returns them in API responses. Consider whether all error details should be client-visible.

⚡ Performance Considerations

Minimal Impact: The changes are primarily structural and don't introduce performance concerns. The explicit result checking adds negligible overhead.

🧪 Test Coverage

Missing Tests: No unit tests found for the watchEmails function or the new error handling paths. Key scenarios to test:

  • Provider returns null result
  • Provider throws exception
  • Database update failures
  • Error message propagation

Consider adding tests in a file like apps/web/__tests__/watch-controller.test.ts:

describe('watchEmails', () => {
  it('should return success when provider succeeds', async () => {
    // Test happy path
  });
  
  it('should return failure when provider returns null', async () => {
    // Test null result scenario
  });
  
  it('should handle provider exceptions gracefully', async () => {
    // Test exception handling
  });
});

🎯 Recommendations

  1. Add unit tests for the new error handling logic
  2. Consider database transactions for watch setup operations
  3. Sanitize error messages exposed to API consumers
  4. Consolidate logging to reduce redundancy
  5. Define explicit types for API response interfaces including errorDetails

Overall Assessment

This is a solid improvement to error handling that makes failures more visible and debuggable. The structured return type is a much better approach than relying on exceptions for control flow. The changes are backward compatible and improve system reliability.

Risk Level: Low - Changes are defensive and improve existing functionality


@vercel
Copy link

vercel bot commented Aug 29, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Updated (UTC)
inbox-zero Ready Ready Preview Aug 29, 2025 1:34pm

Copy link
Contributor

@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

🧹 Nitpick comments (4)
apps/web/app/api/watch/controller.ts (2)

14-16: Prefer a named result type (and add error codes) for reuse and type safety

Use a shared alias and machine-friendly codes to avoid string parsing downstream.

-}: Promise<
-  { success: true; expirationDate: Date } | { success: false; error: string }
-> {
+}: Promise<WatchEmailsResult> {

Add outside the selected range:

export type WatchEmailsResult =
  | { success: true; expirationDate: Date }
  | { success: false; error: string; code: "NO_PROVIDER_RESULT" | "EXCEPTION" };

52-59: Add context to Sentry for triage; keep response minimal

Include identifiers in Sentry extras. Keep returning only the safe message here; avoid passing the raw Error object back to callers.

-    logger.error("Error watching inbox", {
+    logger.error("Error watching inbox", {
       emailAccountId,
       providerName: provider.name,
       error,
     });
-    captureException(error);
-    return { success: false, error: errorMessage };
+    captureException(error, {
+      extra: { emailAccountId, providerName: provider.name },
+    });
+    return { success: false, error: errorMessage, code: "EXCEPTION" };
apps/web/app/api/watch/all/route.ts (1)

108-114: Surface failure metrics or codes for observability

If you adopt error codes in the controller, log them here too (and optionally increment a metric) to track provider failures over time.

-      if (!result.success) {
-        logger.error("Failed to watch emails for account", {
+      if (!result.success) {
+        logger.error("Failed to watch emails for account", {
           emailAccountId: emailAccount.id,
           email: emailAccount.email,
           error: result.error,
+          errorCode: (result as any).code, // if adopting codes
         });
       }
apps/web/app/api/watch/route.ts (1)

96-97: Export a typed GET response for clients

Export a response type so clients don’t infer Date vs string incorrectly.

Add outside the selected range:

export type GetWatchResponse = {
  results: Array<
    | { emailAccountId: string; status: "success"; expirationDate: string }
    | { emailAccountId: string; status: "error"; message: string }
  >;
};
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 31d5f8f and 80c40de.

📒 Files selected for processing (3)
  • apps/web/app/api/watch/all/route.ts (1 hunks)
  • apps/web/app/api/watch/controller.ts (2 hunks)
  • apps/web/app/api/watch/route.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Path aliases: Use @/ for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Leverage TypeScript inference for better DX

Files:

  • apps/web/app/api/watch/route.ts
  • apps/web/app/api/watch/all/route.ts
  • apps/web/app/api/watch/controller.ts
apps/web/app/**

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

NextJS app router structure with (app) directory

Files:

  • apps/web/app/api/watch/route.ts
  • apps/web/app/api/watch/all/route.ts
  • apps/web/app/api/watch/controller.ts
apps/web/app/api/**/route.ts

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/app/api/**/route.ts: Use withAuth for user-level operations
Use withEmailAccount for email-account-level operations
Do NOT use POST API routes for mutations - use server actions instead
No need for try/catch in GET routes when using middleware
Export response types from GET routes

apps/web/app/api/**/route.ts: Wrap all GET API route handlers with withAuth or withEmailAccount middleware for authentication and authorization.
Export response types from GET API routes for type-safe client usage.
Do not use try/catch in GET API routes when using authentication middleware; rely on centralized error handling.

Files:

  • apps/web/app/api/watch/route.ts
  • apps/web/app/api/watch/all/route.ts
!{.cursor/rules/*.mdc}

📄 CodeRabbit inference engine (.cursor/rules/cursor-rules.mdc)

Never place rule files in the project root, in subdirectories outside .cursor/rules, or in any other location

Files:

  • apps/web/app/api/watch/route.ts
  • apps/web/app/api/watch/all/route.ts
  • apps/web/app/api/watch/controller.ts
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/form-handling.mdc)

**/*.ts: The same validation should be done in the server action too
Define validation schemas using Zod

Files:

  • apps/web/app/api/watch/route.ts
  • apps/web/app/api/watch/all/route.ts
  • apps/web/app/api/watch/controller.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)

**/*.{ts,tsx}: Use createScopedLogger for logging in backend TypeScript files
Typically add the logger initialization at the top of the file when using createScopedLogger
Only use .with() on a logger instance within a specific function, not for a global logger

Import Prisma in the project using import prisma from "@/utils/prisma";

**/*.{ts,tsx}: Don't use TypeScript enums.
Don't use TypeScript const enum.
Don't use the TypeScript directive @ts-ignore.
Don't use primitive type aliases or misleading types.
Don't use empty type parameters in type aliases and interfaces.
Don't use any or unknown as type constraints.
Don't use implicit any type on variable declarations.
Don't let variables evolve into any type through reassignments.
Don't use non-null assertions with the ! postfix operator.
Don't misuse the non-null assertion operator (!) in TypeScript files.
Don't use user-defined types.
Use as const instead of literal types and type annotations.
Use export type for types.
Use import type for types.
Don't declare empty interfaces.
Don't merge interfaces and classes unsafely.
Don't use overload signatures that aren't next to each other.
Use the namespace keyword instead of the module keyword to declare TypeScript namespaces.
Don't use TypeScript namespaces.
Don't export imported variables.
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions.
Don't use parameter properties in class constructors.
Use either T[] or Array consistently.
Initialize each enum member value explicitly.
Make sure all enum members are literal values.

Files:

  • apps/web/app/api/watch/route.ts
  • apps/web/app/api/watch/all/route.ts
  • apps/web/app/api/watch/controller.ts
**/api/**/route.ts

📄 CodeRabbit inference engine (.cursor/rules/security.mdc)

**/api/**/route.ts: ALL API routes that handle user data MUST use appropriate authentication and authorization middleware (withAuth or withEmailAccount).
ALL database queries in API routes MUST be scoped to the authenticated user/account (e.g., include userId or emailAccountId in query filters).
Always validate that resources belong to the authenticated user before performing operations (resource ownership validation).
Use withEmailAccount middleware for API routes that operate on a specific email account (i.e., use or require emailAccountId).
Use withAuth middleware for API routes that operate at the user level (i.e., use or require only userId).
Use withError middleware (with proper validation) for public endpoints, custom authentication, or cron endpoints.
Cron endpoints MUST use withError middleware and validate the cron secret using hasCronSecret(request) or hasPostCronSecret(request).
Cron endpoints MUST capture unauthorized attempts with captureException and return a 401 status for unauthorized requests.
All parameters in API routes MUST be validated for type, format, and length before use.
Request bodies in API routes MUST be validated using Zod schemas before use.
All Prisma queries in API routes MUST only return necessary fields and never expose sensitive data.
Error messages in API routes MUST not leak internal information or sensitive data; use generic error messages and SafeError where appropriate.
API routes MUST use a consistent error response format, returning JSON with an error message and status code.
All findUnique and findFirst Prisma calls in API routes MUST include ownership filters (e.g., userId or emailAccountId).
All findMany Prisma calls in API routes MUST be scoped to the authenticated user's data.
Never use direct object references in API routes without ownership checks (prevent IDOR vulnerabilities).
Prevent mass assignment vulnerabilities by only allowing explicitly whitelisted fields in update operations in AP...

Files:

  • apps/web/app/api/watch/route.ts
  • apps/web/app/api/watch/all/route.ts
apps/web/app/api/**/*.{ts,js}

📄 CodeRabbit inference engine (.cursor/rules/security-audit.mdc)

apps/web/app/api/**/*.{ts,js}: All API route handlers in 'apps/web/app/api/' must use authentication middleware: withAuth, withEmailAccount, or withError (with custom authentication logic).
All Prisma queries in API routes must include user/account filtering (e.g., emailAccountId or userId in WHERE clauses) to prevent unauthorized data access.
All parameters used in API routes must be validated before use; do not use parameters from 'params' or request bodies directly in queries without validation.
Request bodies in API routes should use Zod schemas for validation.
API routes should only return necessary fields using Prisma's 'select' and must not include sensitive data in error messages.
Error messages in API routes must not reveal internal details; use generic errors and SafeError for user-facing errors.
All QStash endpoints (API routes called via publishToQstash or publishToQstashQueue) must use verifySignatureAppRouter to verify request authenticity.
All cron endpoints in API routes must use hasCronSecret or hasPostCronSecret for authentication.
Do not hardcode weak or plaintext secrets in API route files; secrets must not be directly assigned as string literals.
Review all new withError usage in API routes to ensure custom authentication is implemented where required.

Files:

  • apps/web/app/api/watch/route.ts
  • apps/web/app/api/watch/all/route.ts
  • apps/web/app/api/watch/controller.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{js,jsx,ts,tsx}: Don't use elements in Next.js projects.
Don't use elements in Next.js projects.
Don't use namespace imports.
Don't access namespace imports dynamically.
Don't use global eval().
Don't use console.
Don't use debugger.
Don't use var.
Don't use with statements in non-strict contexts.
Don't use the arguments object.
Don't use consecutive spaces in regular expression literals.
Don't use the comma operator.
Don't use unnecessary boolean casts.
Don't use unnecessary callbacks with flatMap.
Use for...of statements instead of Array.forEach.
Don't create classes that only have static members (like a static namespace).
Don't use this and super in static contexts.
Don't use unnecessary catch clauses.
Don't use unnecessary constructors.
Don't use unnecessary continue statements.
Don't export empty modules that don't change anything.
Don't use unnecessary escape sequences in regular expression literals.
Don't use unnecessary labels.
Don't use unnecessary nested block statements.
Don't rename imports, exports, and destructured assignments to the same name.
Don't use unnecessary string or template literal concatenation.
Don't use String.raw in template literals when there are no escape sequences.
Don't use useless case statements in switch statements.
Don't use ternary operators when simpler alternatives exist.
Don't use useless this aliasing.
Don't initialize variables to undefined.
Don't use the void operators (they're not familiar).
Use arrow functions instead of function expressions.
Use Date.now() to get milliseconds since the Unix Epoch.
Use .flatMap() instead of map().flat() when possible.
Use literal property access instead of computed property access.
Don't use parseInt() or Number.parseInt() when binary, octal, or hexadecimal literals work.
Use concise optional chaining instead of chained logical expressions.
Use regular expression literals instead of the RegExp constructor when possible.
Don't use number literal object member names th...

Files:

  • apps/web/app/api/watch/route.ts
  • apps/web/app/api/watch/all/route.ts
  • apps/web/app/api/watch/controller.ts
!pages/_document.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

!pages/_document.{js,jsx,ts,tsx}: Don't import next/document outside of pages/_document.jsx in Next.js projects.
Don't import next/document outside of pages/_document.jsx in Next.js projects.

Files:

  • apps/web/app/api/watch/route.ts
  • apps/web/app/api/watch/all/route.ts
  • apps/web/app/api/watch/controller.ts
🧠 Learnings (1)
📚 Learning: 2025-07-18T15:04:30.467Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-18T15:04:30.467Z
Learning: Applies to apps/web/app/api/**/route.ts : Use `withEmailAccount` for email-account-level operations

Applied to files:

  • apps/web/app/api/watch/all/route.ts
🧬 Code graph analysis (2)
apps/web/app/api/watch/route.ts (2)
apps/web/app/api/watch/controller.ts (1)
  • watchEmails (8-61)
apps/web/app/api/outlook/webhook/logger.ts (1)
  • logger (3-3)
apps/web/app/api/watch/all/route.ts (2)
apps/web/app/api/watch/controller.ts (1)
  • watchEmails (8-61)
apps/web/app/api/outlook/webhook/logger.ts (1)
  • logger (3-3)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: claude-review
  • GitHub Check: Analyze (actions)
🔇 Additional comments (3)
apps/web/app/api/watch/all/route.ts (2)

103-107: LGTM: consuming the structured watchEmails result

This aligns the route with the controller’s discriminated-union return type.


148-155: Wrap QStash-triggered POST with signature verification
If this endpoint is invoked via QStash, wrap the exported handler in verifySignatureAppRouter (you can still keep hasPostCronSecret as defense-in-depth). Please confirm whether /api/watch/all is scheduled via QStash.

apps/web/app/api/watch/route.ts (1)

57-61: LGTM: switched to result object from controller

The refactor reads clean and matches the controller’s API.

Comment on lines +41 to +49
return { success: true, expirationDate: result.expirationDate };
} else {
const errorMessage = "Provider returned no result for watch setup";
logger.error("Error watching inbox", {
emailAccountId,
providerName: provider.name,
error: errorMessage,
});
return { success: false, error: errorMessage };
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Return structured failure with a stable error code

This eases logging/analytics and allows clients to branch without parsing messages.

-      return { success: true, expirationDate: result.expirationDate };
+      return { success: true, expirationDate: result.expirationDate };
     } else {
-      const errorMessage = "Provider returned no result for watch setup";
+      const errorMessage = "Provider returned no result for watch setup";
       logger.error("Error watching inbox", {
         emailAccountId,
         providerName: provider.name,
         error: errorMessage,
       });
-      return { success: false, error: errorMessage };
+      return { success: false, error: errorMessage, code: "NO_PROVIDER_RESULT" };
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return { success: true, expirationDate: result.expirationDate };
} else {
const errorMessage = "Provider returned no result for watch setup";
logger.error("Error watching inbox", {
emailAccountId,
providerName: provider.name,
error: errorMessage,
});
return { success: false, error: errorMessage };
return { success: true, expirationDate: result.expirationDate };
} else {
const errorMessage = "Provider returned no result for watch setup";
logger.error("Error watching inbox", {
emailAccountId,
providerName: provider.name,
error: errorMessage,
});
return { success: false, error: errorMessage, code: "NO_PROVIDER_RESULT" };
}
🤖 Prompt for AI Agents
In apps/web/app/api/watch/controller.ts around lines 41 to 49, the handler
currently returns a freeform error message when the provider returns no result;
change this to return a structured failure with a stable error code and message
(e.g. error: { code: "NO_PROVIDER_RESULT", message: "Provider returned no result
for watch setup" }) and update the logger to include that error code
(logger.error(..., { ..., errorCode: "NO_PROVIDER_RESULT", error: errorMessage
})); ensure the returned shape matches the API/type definitions so clients can
branch on error.code instead of parsing text.

Comment on lines +62 to 67
if (result.success) {
results.push({
emailAccountId,
status: "success",
expirationDate,
expirationDate: result.expirationDate,
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Serialize Date to string in API response

Avoid leaking a Date instance type over the wire; return ISO string for consistent client typing.

        results.push({
          emailAccountId,
          status: "success",
-          expirationDate: result.expirationDate,
+          expirationDate: result.expirationDate.toISOString(),
        });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (result.success) {
results.push({
emailAccountId,
status: "success",
expirationDate,
expirationDate: result.expirationDate,
});
if (result.success) {
results.push({
emailAccountId,
status: "success",
expirationDate: result.expirationDate.toISOString(),
});
🤖 Prompt for AI Agents
In apps/web/app/api/watch/route.ts around lines 62 to 67, the API is returning a
Date instance (result.expirationDate) directly in the JSON response; change this
to serialize the date to a string (e.g., result.expirationDate?.toISOString() or
null/undefined as appropriate) so clients always receive an ISO date string;
update any related types/interfaces to reflect the string type if needed.

Comment on lines +69 to +73
logger.error("Error watching inbox for account", {
emailAccountId,
provider: account.provider,
error: result.error,
});
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Do not expose internal error details in API responses

Guideline: API routes must not reveal internal details. Log full context server-side; return a generic message to clients.

-        logger.error("Error watching inbox for account", {
+        logger.error("Error watching inbox for account", {
           emailAccountId,
           provider: account.provider,
           error: result.error,
         });
         results.push({
           emailAccountId,
           status: "error",
           message: "Failed to set up watch for this account.",
-          errorDetails: result.error,
         });

Also applies to: 74-79

@elie222 elie222 merged commit 1b02c91 into main Aug 29, 2025
17 checks passed
@elie222 elie222 deleted the chore/outlook-watch-logging branch August 29, 2025 14:15
This was referenced Nov 6, 2025
@coderabbitai coderabbitai bot mentioned this pull request Dec 17, 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.

1 participant