Skip to content

fix: improve error and handler log serialization#826

Merged
TomerFi merged 2 commits intomainfrom
fix/error-log-serialization
Feb 23, 2026
Merged

fix: improve error and handler log serialization#826
TomerFi merged 2 commits intomainfrom
fix/error-log-serialization

Conversation

@TomerFi
Copy link
Owner

@TomerFi TomerFi commented Feb 23, 2026

Summary

  • Deserialize error event payloads in the catch block and probot.onError to log repo name, event type, and PR number instead of truncated [Object]
  • Add [owner/repo#number] context to all handler start, complete, and error log lines across all 6 handlers
  • Fix API non-200 response logging that destructured an undefined message field from Octokit responses
  • Downgrade noisy "no config found" log from info to debug level, with repo context added

Test plan

  • All 107 tests passing locally (Node 22)
  • 99.32% code coverage

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced logging across handlers with richer, consistent contextual tags (repository, event, PR) for clearer diagnostics.
    • Improved error messages and status reporting to aid troubleshooting without changing control flow.
  • Tests

    • Expanded test payloads to include repository and PR metadata so tests reflect richer runtime context.

- Deserialize error event payload in catch block to log repo name,
  event type, and PR number instead of truncated [Object]
- Add repo and PR context to all handler start/complete/error logs
- Fix API non-200 response logging that referenced undefined `message`
- Downgrade "no config found" from info to debug with repo context
- Fix probot.onError to properly serialize error details
- Update test fixtures with repository and PR number in mock payloads

Signed-off-by: Tomer Figenblat <[email protected]>
Co-authored-by: Cursor <[email protected]>
@auto-me-bot auto-me-bot bot added the status: needs review Pull request needs a review label Feb 23, 2026
@snyk-io
Copy link

snyk-io bot commented Feb 23, 2026

Snyk checks have passed. No issues have been found so far.

Status Scanner Critical High Medium Low Total (0)
Open Source Security 0 0 0 0 0 issues
Code Security 0 0 0 0 0 issues

💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse.

@coderabbitai
Copy link

coderabbitai bot commented Feb 23, 2026

📝 Walkthrough

Walkthrough

The PR standardizes and enriches logging across handlers and core modules by adding context-aware "tag" strings (handler, repository, PR/issue) and extracting event metadata in error handlers. Test fixtures were updated to include repository full_name and PR numbers to support the richer logging context.

Changes

Cohort / File(s) Summary
Core error & bot runtime
src/app-runner.js, src/auto-me-bot.js
Enhanced error catch logging to extract repository, event (name/action), and issue/PR number from error event payloads; replaced plain logs with structured objects and adjusted log level when config is missing.
Handler logging (tagged messages)
src/handlers/pr-auto-approve.js, src/handlers/pr-conventional-commits.js, src/handlers/pr-conventional-title.js, src/handlers/pr-signed-commits.js, src/handlers/pr-tasks-list.js
Introduced a tag (handler name + repo + PR#) and replaced start/finalize/complete/error logs to use the tag for consistent, contextual messages; no functional control-flow changes.
Handler logging + signature updates
src/handlers/pr-lifecycle-labels.js
Added tag and propagated it into helper calls; updated helper signatures to getLifecycleLabel(context, tag) and workThemLabels(context, config, report, tag) and switched logging to use tag and error.message.
Tests: richer payload fixtures
tests/auto-me-bot.test.js, tests/handlers/pr-auto-approve.test.js, tests/handlers/pr-conventional-commits.test.js, tests/handlers/pr-conventional-title.test.js, tests/handlers/pr-lifecycle-labels.test.js, tests/handlers/pr-signed-commits.test.js, tests/handlers/pr-tasks-list.test.js
Augmented test contexts to include payload.repository.full_name and PR number fields where applicable so handlers receive the metadata expected by new logging/tagging logic.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

🐰 Logs trimmed with ribbons, neat and bright,
A tag for every handler—what a sight!
Repo and PR dance in each line,
Errors whisper context, tidy and fine.
Hopping off now—good debugging, delight!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 54.55% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly matches the main objective of improving error and handler log serialization across the codebase, and is clear and specific about the change.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/error-log-serialization

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.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/handlers/pr-lifecycle-labels.js (1)

226-233: ⚠️ Potential issue | 🟡 Minor

Missing log line for addLabels non-200 response — inconsistent with every other non-200 path in this file.

All other API non-200 paths in this handler (listReviews, getBranchProtection, removeLabel) emit context.log.error(...). The addLabels .then() silently updates the report without any log, making it the only unlogged API failure path. As per coding guidelines, API errors must always be caught and reported.

🛠️ Proposed fix
 await context.octokit.rest.issues.addLabels(context.repo({issue_number: context.payload.pull_request.number, labels: [addLabel]}))
     .then(resp => {
         if (resp.status !== 200) {
+            context.log.error(`${tag} got unexpected status ${resp.status}`);
             report.conclusion = 'failure';
             report.output.title = 'Failed to add the label';
             report.output.summary = 'This might be an internal time out, please try again';
         }
     })
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/handlers/pr-lifecycle-labels.js` around lines 226 - 233, The addLabels
success check currently updates the report on non-200 responses but doesn't log
the failure; modify the addLabels response handler (the call to
context.octokit.rest.issues.addLabels) to emit a context.log.error with a clear
message and include response/status details when resp.status !== 200 (mirror
other handlers like listReviews/getBranchProtection/removeLabel), ensuring
report.conclusion/report.output remain set as before and the log includes
identifying info such as the pull_request number and the returned
resp/status/body.
🧹 Nitpick comments (2)
src/handlers/pr-conventional-title.js (1)

27-28: Consider extracting the repeated tag construction into a shared helper.

All six handlers share the exact same inline template literal. A tiny utility would eliminate the duplication:

// e.g., src/handlers/handler-utils.js
+export function buildTag(handlerName, context) {
+    return `${handlerName} [${context.payload.repository.full_name}#${context.payload.pull_request.number}]`;
+}

Each handler would then become:

+import { buildTag } from './handler-utils.js';
 ...
-const tag = `${running_handler} [${context.payload.repository.full_name}#${context.payload.pull_request.number}]`;
+const tag = buildTag(running_handler, context);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/handlers/pr-conventional-title.js` around lines 27 - 28, Multiple
handlers duplicate the same tag construction using the template literal with
running_handler and context.payload details; extract that into a shared helper
function (e.g., buildHandlerTag or formatHandlerTag) and replace the inline
construction in each handler where tag is defined (references: running_handler,
context.payload.repository.full_name, context.payload.pull_request.number, and
context.log.info) so each handler calls the helper to produce the tag before
logging.
src/app-runner.js (1)

38-47: Consider extracting the shared event-context helper

The four lines at 38-41 here are byte-for-byte identical to src/auto-me-bot.js lines 56-59. A shared utility (e.g. extractEventContext(error)) would keep both error-logging paths consistent and make future changes (like the number fallback fix above) a single-site update.

♻️ Suggested helper (e.g. in a new src/log-utils.js)
+// src/log-utils.js
+export function extractEventContext(error) {
+    const evt = error?.event;
+    return {
+        repo: evt?.payload?.repository?.full_name,
+        action: evt ? `${evt.name}.${evt.payload?.action}` : 'unknown',
+        num: evt?.payload?.number ?? evt?.payload?.pull_request?.number,
+    };
+}

Then in both callers:

-        const evt = error.event;
-        const repo = evt?.payload?.repository?.full_name;
-        const action = evt ? `${evt.name}.${evt.payload?.action}` : 'unknown';
-        const num = evt?.payload?.number;
+        const { repo, action, num } = extractEventContext(error);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/app-runner.js` around lines 38 - 47, Extract the duplicated event-context
logic (evt, repo, action, num) into a shared helper like
extractEventContext(error) placed in a new module (e.g., src/log-utils.js), have
it accept the error object and return {evt, repo, action, num} or a formatted
string; then replace the four identical lines in src/app-runner.js and the
matching block in src/auto-me-bot.js to call extractEventContext(error) and use
its return values for logging so both callers share the same implementation and
future fixes are centralized.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/app-runner.js`:
- Around line 39-41: The variable num is set from evt?.payload?.number which is
undefined for pull_request_review events; update the assignment of num (in
src/app-runner.js where evt, repo and action are defined) to fall back to
evt?.payload?.pull_request?.number when evt?.payload?.number is falsy so
pull_request_review events get the correct PR number; ensure you only change the
num initialization to include this fallback and keep the rest of the surrounding
logic intact.

In `@src/auto-me-bot.js`:
- Around line 56-59: The PR number extraction uses evt?.payload?.number which is
undefined for pull_request_review events; update the logic that computes num
(and any logging that uses it) to fall back to evt.payload.pull_request.number
when payload.number is absent, e.g. set num to evt?.payload?.number ??
evt?.payload?.pull_request?.number so pull request review webhooks log the
correct PR number; ensure this change is applied where num is computed alongside
evt, repo, and action in auto-me-bot.js.
- Around line 60-63: The log call drops err.errors because Pino ignores surplus
args; change the probot.log.error call to pass a single object as the first
argument containing contextual fields and the mapped nested errors (e.g.,
include repo, event/action, num, message and an errors array from (err.errors ??
[]).map(...)) and then the formatted message string as the second arg; update
the call site where probot.log.error is invoked so the error details are merged
into the JSON log line rather than spread as extra arguments.

---

Outside diff comments:
In `@src/handlers/pr-lifecycle-labels.js`:
- Around line 226-233: The addLabels success check currently updates the report
on non-200 responses but doesn't log the failure; modify the addLabels response
handler (the call to context.octokit.rest.issues.addLabels) to emit a
context.log.error with a clear message and include response/status details when
resp.status !== 200 (mirror other handlers like
listReviews/getBranchProtection/removeLabel), ensuring
report.conclusion/report.output remain set as before and the log includes
identifying info such as the pull_request number and the returned
resp/status/body.

---

Nitpick comments:
In `@src/app-runner.js`:
- Around line 38-47: Extract the duplicated event-context logic (evt, repo,
action, num) into a shared helper like extractEventContext(error) placed in a
new module (e.g., src/log-utils.js), have it accept the error object and return
{evt, repo, action, num} or a formatted string; then replace the four identical
lines in src/app-runner.js and the matching block in src/auto-me-bot.js to call
extractEventContext(error) and use its return values for logging so both callers
share the same implementation and future fixes are centralized.

In `@src/handlers/pr-conventional-title.js`:
- Around line 27-28: Multiple handlers duplicate the same tag construction using
the template literal with running_handler and context.payload details; extract
that into a shared helper function (e.g., buildHandlerTag or formatHandlerTag)
and replace the inline construction in each handler where tag is defined
(references: running_handler, context.payload.repository.full_name,
context.payload.pull_request.number, and context.log.info) so each handler calls
the helper to produce the tag before logging.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 788bc84 and e0f3ed7.

📒 Files selected for processing (15)
  • src/app-runner.js
  • src/auto-me-bot.js
  • src/handlers/pr-auto-approve.js
  • src/handlers/pr-conventional-commits.js
  • src/handlers/pr-conventional-title.js
  • src/handlers/pr-lifecycle-labels.js
  • src/handlers/pr-signed-commits.js
  • src/handlers/pr-tasks-list.js
  • tests/auto-me-bot.test.js
  • tests/handlers/pr-auto-approve.test.js
  • tests/handlers/pr-conventional-commits.test.js
  • tests/handlers/pr-conventional-title.test.js
  • tests/handlers/pr-lifecycle-labels.test.js
  • tests/handlers/pr-signed-commits.test.js
  • tests/handlers/pr-tasks-list.test.js

@auto-me-bot auto-me-bot bot added status: review started Pull review in progress and removed status: needs review Pull request needs a review labels Feb 23, 2026
- payload.number is undefined for pull_request_review events; fall back
  to payload.pull_request.number in both error handlers.
- Pino silently drops spread args after the message string; pass nested
  errors as a merge object instead.

Signed-off-by: Tomer Figenblat <[email protected]>
Co-authored-by: Cursor <[email protected]>
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.

♻️ Duplicate comments (1)
src/auto-me-bot.js (1)

56-59: Both previously flagged issues are addressed — LGTM.

The pull_request_review number fallback (?? evt?.payload?.pull_request?.number) resolves the past comment about payload.number being undefined for review events, and the extraction pattern is now identical to src/app-runner.js lines 37–40.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/auto-me-bot.js` around lines 56 - 59, The extraction of event metadata
(variables evt, repo, action, num) is correct now and mirrors
src/app-runner.js's pattern; no code changes are required — keep the current
fallback for num as evt?.payload?.number ?? evt?.payload?.pull_request?.number
and the action computation using `${evt.name}.${evt.payload?.action}` to handle
review events consistently.
🧹 Nitpick comments (1)
src/auto-me-bot.js (1)

60-63: Consider omitting errors field when empty to reduce log noise.

{ errors: [] } is always emitted even when there are no nested errors. Conditionally including it keeps log output cleaner.

🔧 Suggested tweak
-    { errors: (err.errors ?? []).map(e => `${e.status} ${e.message}`) },
+    { ...(err.errors?.length && { errors: err.errors.map(e => `${e.status} ${e.message}`) }) },
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/auto-me-bot.js` around lines 60 - 63, The current probot.log.error call
always includes an errors field even when empty; modify the code around
probot.log.error so you build the log payload first (e.g., create a variable
like payload or meta), compute const nested = (err.errors ?? []).map(e =>
`${e.status} ${e.message}`), and only attach payload.errors = nested when
nested.length > 0, then call probot.log.error(payload, `[repo=${repo},
event=${action}, #${num}] ${err.message}`) to avoid emitting { errors: [] }
noise.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@src/auto-me-bot.js`:
- Around line 56-59: The extraction of event metadata (variables evt, repo,
action, num) is correct now and mirrors src/app-runner.js's pattern; no code
changes are required — keep the current fallback for num as evt?.payload?.number
?? evt?.payload?.pull_request?.number and the action computation using
`${evt.name}.${evt.payload?.action}` to handle review events consistently.

---

Nitpick comments:
In `@src/auto-me-bot.js`:
- Around line 60-63: The current probot.log.error call always includes an errors
field even when empty; modify the code around probot.log.error so you build the
log payload first (e.g., create a variable like payload or meta), compute const
nested = (err.errors ?? []).map(e => `${e.status} ${e.message}`), and only
attach payload.errors = nested when nested.length > 0, then call
probot.log.error(payload, `[repo=${repo}, event=${action}, #${num}]
${err.message}`) to avoid emitting { errors: [] } noise.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e0f3ed7 and 418db2b.

📒 Files selected for processing (2)
  • src/app-runner.js
  • src/auto-me-bot.js
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/app-runner.js

@coderabbitai
Copy link

coderabbitai bot commented Feb 23, 2026

✅ Actions performed

Comments resolved. Auto-approval is disabled; enable reviews.request_changes_workflow to approve automatically.

2 similar comments
@coderabbitai
Copy link

coderabbitai bot commented Feb 23, 2026

✅ Actions performed

Comments resolved. Auto-approval is disabled; enable reviews.request_changes_workflow to approve automatically.

@coderabbitai
Copy link

coderabbitai bot commented Feb 23, 2026

✅ Actions performed

Comments resolved. Auto-approval is disabled; enable reviews.request_changes_workflow to approve automatically.

@TomerFi TomerFi merged commit 627d45a into main Feb 23, 2026
10 checks passed
@TomerFi TomerFi deleted the fix/error-log-serialization branch February 23, 2026 17:57
@auto-me-bot auto-me-bot bot added status: merged Pull request merged and removed status: review started Pull review in progress labels Feb 23, 2026
@codecov
Copy link

codecov bot commented Feb 23, 2026

Codecov Report

❌ Patch coverage is 98.36066% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 99.32%. Comparing base (788bc84) to head (418db2b).
⚠️ Report is 4 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #826      +/-   ##
==========================================
+ Coverage   99.21%   99.32%   +0.10%     
==========================================
  Files           8        8              
  Lines        1022     1038      +16     
==========================================
+ Hits         1014     1031      +17     
+ Misses          8        7       -1     
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status: merged Pull request merged

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant