Skip to content

# 🛑 Standardize API Error Handling with Global Middleware #333

Description

@KhairnarLokesh

🛑 Standardize API Error Handling with Global Middleware

📌 Title

Refactor Controllers to Use Centralized Global Error Handling Middleware


🚨 The Issue

Currently, controllers use:

  • Individual try-catch blocks
  • Inconsistent error response formats
  • Mixed status codes
  • Unpredictable error structures

This causes:

  • ❌ Frontend parsing issues
  • ❌ Inconsistent error UX
  • ❌ Hard-to-maintain controllers
  • ❌ Duplicated error logic
  • ❌ Reduced debugging clarity

The API is not predictable for frontend consumption.


🎯 Goal

Implement a global error-handling middleware and refactor all controllers to:

  • Remove redundant try-catch blocks
  • Use next(error) pattern
  • Standardize error response format
  • Ensure consistent status codes
  • Improve maintainability

🧱 Implementation Plan


1️⃣ Create Global Error Middleware

📁 Create:

middlewares/errorHandler.js

Example Structure:

function errorHandler(err, req, res, next) {
  console.error(err);

  const statusCode = err.statusCode || 500;

  res.status(statusCode).json({
    success: false,
    message: err.message || 'Internal Server Error',
    errorCode: err.code || 'SERVER_ERROR',
    timestamp: new Date().toISOString()
  });
}

module.exports = errorHandler;

2️⃣ Create Custom Error Utility

📁 Create:

utils/ApiError.js

Example:

class ApiError extends Error {
  constructor(statusCode, message, code = null) {
    super(message);
    this.statusCode = statusCode;
    this.code = code;
  }
}

module.exports = ApiError;

3️⃣ Refactor Controllers

Replace:

try {
  ...
} catch (error) {
  res.status(500).json({ error: error.message });
}

With:

if (!evidence) {
  return next(new ApiError(404, 'Evidence not found', 'EVIDENCE_NOT_FOUND'));
}

Let middleware handle the response.


4️⃣ Register Middleware in App

In:

app.js

Add at bottom:

app.use(errorHandler);

⚠ Must be after all routes.


📦 Standard Error Response Format

All errors should follow:

{
  "success": false,
  "message": "Evidence not found",
  "errorCode": "EVIDENCE_NOT_FOUND",
  "timestamp": "2026-02-25T14:00:00Z"
}

🧪 Refactor Scope

Apply to all controllers:

  • evidenceUploadController
  • evidenceIntegrityController
  • evidenceBlockchainController
  • evidenceJudicialController
  • evidenceQueryController
  • Any remaining legacy controllers

🧠 Error Categories to Standardize

Category Status Code
Validation Error 400
Unauthorized 401
Forbidden 403
Not Found 404
Conflict 409
Blockchain Failure 502
Internal Server Error 500

🔐 Benefits

This change will:

  • Improve frontend predictability
  • Reduce controller boilerplate
  • Enforce clean architecture
  • Simplify debugging
  • Enable centralized logging
  • Allow future integration with monitoring tools (e.g., Sentry)

🧪 Testing Requirements

  • Simulate validation error
  • Simulate DB failure
  • Simulate blockchain failure
  • Simulate missing record
  • Confirm consistent JSON response
  • Confirm no controller sends manual error responses

📊 Acceptance Criteria

  • errorHandler middleware created
  • ApiError utility created
  • Controllers refactored
  • No manual res.status(...).json error responses
  • All errors use consistent format
  • Status codes standardized
  • Middleware registered correctly
  • API remains fully functional

🏁 Expected Outcome

A clean, predictable, and production-grade API error system that:

  • Centralizes error handling
  • Standardizes responses
  • Improves frontend integration
  • Enhances long-term maintainability

Priority: High
Type: Architectural Refactor
Impact: API Stability & Frontend Predictability

Metadata

Metadata

Labels

HARDbig features, complex refactors, heavy debuggingOSCG26backendphase-2

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions