Skip to content

refactor: catch body-parser JSON syntax errors and improve global error logs #113

Open
KGFCH2 wants to merge 1 commit into
kunalverma2512:mainfrom
KGFCH2:refactor/api-error-handler
Open

refactor: catch body-parser JSON syntax errors and improve global error logs #113
KGFCH2 wants to merge 1 commit into
kunalverma2512:mainfrom
KGFCH2:refactor/api-error-handler

Conversation

@KGFCH2

@KGFCH2 KGFCH2 commented May 31, 2026

Copy link
Copy Markdown
Contributor

Related Issue

Closes #112

Summary

Catches bad request body payload parsing formats gracefully.

Changes Made

  • Modified errorHandler.js to handle SyntaxError with status 400.

Summary by CodeRabbit

  • Bug Fixes
    • Enhanced error handling for malformed JSON in API requests with clearer error responses.
    • Improved server-side logging of internal errors to aid troubleshooting and debugging.

@vercel

vercel Bot commented May 31, 2026

Copy link
Copy Markdown

@KGFCH2 is attempting to deploy a commit to the Kunal Verma's projects Team on Vercel.

A member of the Team first needs to authorize it.

@github-actions

Copy link
Copy Markdown

🚀 PR Received Successfully

Hello @KGFCH2,

Thank you for taking the initiative to contribute to this project.

Please ensure that your PR follows all project guidelines properly before requesting review.

⚠️ Important Instructions

  • Maintain proper code quality and structure
  • Do not make unnecessary changes/files
  • Ensure responsiveness across devices
  • Follow existing project conventions strictly
  • Attach screenshots/videos for UI-related changes
  • Resolve merge conflicts before requesting review
  • Avoid AI-generated low quality PRs or copied implementations

📌 Mandatory for GSSoC'26 Participants

Joining the community group and announcement channel is compulsory for all contributors participating through GSSoC'26.

Failure to follow contribution guidelines may lead to PR rejection.

We appreciate your effort and wish you a great open-source journey ahead. ✨

@coderabbitai

coderabbitai Bot commented May 31, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The error handler middleware is enhanced to log internal server errors and handle malformed JSON request bodies uniformly. Internal errors are logged to the server console with request details, and parsing syntax errors now return a structured JSON 400 response instead of raw HTML error output.

Changes

Error Handler Enhancements

Layer / File(s) Summary
Error logging and malformed JSON handling
server/middlewares/errorHandler.js
Error handler adds console logging for 500-level errors when err.statusCode is missing or equals 500, including request method and URL. A new branch before the existing ApiError handling intercepts malformed JSON parsing errors (SyntaxError with err.status === 400 and a body property) and returns a structured "Invalid JSON syntax" 400 response.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

🐰 A handler refined with a logging gaze,
Now catches bad JSON in countless ways,
500s and syntax, both tamed and bright,
Structured responses, forever right! 🎯

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is sparse and lacks the structured template format with sections like Type of Change, Testing, and Checklist from the repository template. Expand the description to follow the template structure, including Type of Change checkboxes, Testing verification section, and the full checklist items.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main changes: catching body-parser JSON syntax errors and improving global error logs in the errorHandler.
Linked Issues check ✅ Passed The changes directly address issue #112 by implementing SyntaxError handling for malformed JSON with 400 status responses and improving error logging as requested.
Out of Scope Changes check ✅ Passed All changes in errorHandler.js are directly scoped to handle JSON parsing errors and improve error logs, which aligns with the objectives of issue #112.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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 coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
server/middlewares/errorHandler.js (1)

16-21: Harden malformed JSON detection in server/middlewares/errorHandler.js

The current condition (err instanceof SyntaxError && err.status === 400 && 'body' in err) matches the express.json()/body-parser invalid-JSON error fields, but adding err.type === 'entity.parse.failed' would prevent accidentally treating unrelated SyntaxErrors with status/body as malformed JSON.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@server/middlewares/errorHandler.js` around lines 16 - 21, Tighten the
malformed JSON check in server/middlewares/errorHandler.js by adding a check for
err.type === 'entity.parse.failed' to the existing condition that currently
reads (err instanceof SyntaxError && err.status === 400 && 'body' in err);
update the conditional inside the error handling block (the code that sets
statusCode = 400, message = "Invalid JSON syntax in request body.", and
errorResponse.message) to only run when err.type equals 'entity.parse.failed' as
well, ensuring unrelated SyntaxError instances are not misclassified as
malformed JSON.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@server/middlewares/errorHandler.js`:
- Around line 11-14: The current logging block using if (!err.statusCode ||
err.statusCode === 500) wrongly treats errors without statusCode as 500; move
the console.error call so it runs only after you determine the effective
response status for the error (i.e., after the error-type checks that map
SyntaxError, Mongoose, JWT, etc. to 400/401/409), and log only when the resolved
status is 500; update references to err, req.method and req.originalUrl (and the
errorHandler function) so the message still includes the original request
context and the full error object for genuine internal server errors.

---

Nitpick comments:
In `@server/middlewares/errorHandler.js`:
- Around line 16-21: Tighten the malformed JSON check in
server/middlewares/errorHandler.js by adding a check for err.type ===
'entity.parse.failed' to the existing condition that currently reads (err
instanceof SyntaxError && err.status === 400 && 'body' in err); update the
conditional inside the error handling block (the code that sets statusCode =
400, message = "Invalid JSON syntax in request body.", and
errorResponse.message) to only run when err.type equals 'entity.parse.failed' as
well, ensuring unrelated SyntaxError instances are not misclassified as
malformed JSON.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 24c0072c-66f9-4525-9195-12e44166f1cd

📥 Commits

Reviewing files that changed from the base of the PR and between 9390870 and 90f6f90.

📒 Files selected for processing (1)
  • server/middlewares/errorHandler.js

Comment on lines +11 to +14
// Log 500 internal errors to the server console for debuggability
if (!err.statusCode || err.statusCode === 500) {
console.error(`[Error] Internal Server Error on ${req.method} ${req.originalUrl}:`, err);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Logging logic incorrectly flags client errors as internal server errors.

The condition !err.statusCode will match errors that don't have a statusCode property, including the newly handled SyntaxError (which has err.status), Mongoose errors, and JWT errors. These will be logged as "Internal Server Error" even though they ultimately return 400/401/409 status codes.

Move the logging after the error-type determination so only genuine 500-level errors are logged.

🔧 Proposed fix
  let errorResponse = {
    success: false,
    message: message
  };

- // Log 500 internal errors to the server console for debuggability
- if (!err.statusCode || err.statusCode === 500) {
-   console.error(`[Error] Internal Server Error on ${req.method} ${req.originalUrl}:`, err);
- }
-
  // Handle express malformed JSON parsing error
  if (err instanceof SyntaxError && err.status === 400 && 'body' in err) {
    statusCode = 400;
    message = "Invalid JSON syntax in request body.";
    errorResponse.message = message;
  }
  // Handle ApiError
  else if (err instanceof ApiError) {
    statusCode = err.statusCode;
    message = err.message;
    errorResponse.message = message;
  }
  // Handle Mongoose ValidationError
  else if (err.name === "ValidationError") {
    statusCode = 400;
    const messages = Object.values(err.errors).map(val => val.message);
    message = `Validation Error: ${messages.join(", ")}`;
    errorResponse.message = message;
  }
  // Handle Mongoose CastError (invalid ObjectId)
  else if (err.name === "CastError") {
    statusCode = 400;
    message = `Invalid ${err.path}: ${err.value}`;
    errorResponse.message = message;
  }
  // Handle Mongoose duplicate key error
  else if (err.code === 11000) {
    statusCode = 409;
    const field = Object.keys(err.keyValue)[0];
    message = `${field} already exists.`;
    errorResponse.message = message;
  }
  // Handle JWT errors
  else if (err.name === "JsonWebTokenError") {
    statusCode = 401;
    message = "Invalid token.";
    errorResponse.message = message;
  }
  else if (err.name === "TokenExpiredError") {
    statusCode = 401;
    message = "Token expired.";
    errorResponse.message = message;
  }
  // Handle other errors
  else if (err.message) {
    message = err.message;
    errorResponse.message = message;
  }

+ // Log 500 internal errors to the server console for debuggability
+ if (statusCode === 500) {
+   console.error(`[Error] Internal Server Error on ${req.method} ${req.originalUrl}:`, err);
+ }
+
  // Include stack trace in development mode
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@server/middlewares/errorHandler.js` around lines 11 - 14, The current logging
block using if (!err.statusCode || err.statusCode === 500) wrongly treats errors
without statusCode as 500; move the console.error call so it runs only after you
determine the effective response status for the error (i.e., after the
error-type checks that map SyntaxError, Mongoose, JWT, etc. to 400/401/409), and
log only when the resolved status is 500; update references to err, req.method
and req.originalUrl (and the errorHandler function) so the message still
includes the original request context and the full error object for genuine
internal server errors.

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.

[Bug]: refactor: Intercept JSON parsing syntax exceptions on global handler

1 participant