All files / src/api errors.js

32.09% Statements 26/81
66.66% Branches 2/3
11.11% Functions 1/9
32.09% Lines 26/81

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186                  1x             1x                               1x               1x           1x           1x       1x           1x         1x       1x           1x         1x       1x           1x         1x       1x           1x         1x       1x             10x 10x 2x 2x 2x                 2x 10x                                                                                                
/**
 * API Error Handling for Coherent.js
 * @fileoverview Standardized error classes and handling utilities
 */
 
/**
 * Base API Error class
 * @extends Error
 */
class ApiError extends Error {
  /**
   * Create an API error
   * @param {string} message - Error message
   * @param {number} statusCode - HTTP status code
   * @param {Object} details - Additional error details
   */
  constructor(message, statusCode = 500, details = {}) {
    super(message);
    this.name = 'ApiError';
    this.statusCode = statusCode;
    this.details = details;
    
    // Ensure proper stack trace
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, ApiError);
    }
  }
  
  /**
   * Convert error to JSON-serializable object
   * @returns {Object} Error object
   */
  toJSON() {
    return {
      error: this.name,
      message: this.message,
      statusCode: this.statusCode,
      details: this.details
    };
  }
}
 
/**
 * Validation Error class
 * @extends ApiError
 */
class ValidationError extends ApiError {
  /**
   * Create a validation error
   * @param {Object} errors - Validation errors
   * @param {string} message - Error message
   */
  constructor(errors, message = 'Validation failed') {
    super(message, 400, { errors });
    this.name = 'ValidationError';
  }
}
 
/**
 * Authentication Error class
 * @extends ApiError
 */
class AuthenticationError extends ApiError {
  /**
   * Create an authentication error
   * @param {string} message - Error message
   */
  constructor(message = 'Authentication required') {
    super(message, 401);
    this.name = 'AuthenticationError';
  }
}
 
/**
 * Authorization Error class
 * @extends ApiError
 */
class AuthorizationError extends ApiError {
  /**
   * Create an authorization error
   * @param {string} message - Error message
   */
  constructor(message = 'Access denied') {
    super(message, 403);
    this.name = 'AuthorizationError';
  }
}
 
/**
 * Not Found Error class
 * @extends ApiError
 */
class NotFoundError extends ApiError {
  /**
   * Create a not found error
   * @param {string} message - Error message
   */
  constructor(message = 'Resource not found') {
    super(message, 404);
    this.name = 'NotFoundError';
  }
}
 
/**
 * Conflict Error class
 * @extends ApiError
 */
class ConflictError extends ApiError {
  /**
   * Create a conflict error
   * @param {string} message - Error message
   */
  constructor(message = 'Resource conflict') {
    super(message, 409);
    this.name = 'ConflictError';
  }
}
 
/**
 * Create error handling middleware
 * @param {Function} handler - Error handler function
 * @returns {Function} Middleware function
 */
function withErrorHandling(handler) {
  return async (req, res, next) => {
    try {
      return await handler(req, res, next);
    } catch (error) {
      // If it's already an API error, use it as-is
      if (error instanceof ApiError) {
        throw error;
      }
      
      // Otherwise, wrap it as a generic server error
      throw new ApiError(error.message || 'Internal server error', 500);
    }
  };
}
 
/**
 * Global error handler middleware
 * @returns {Function} Express error handler middleware
 */
function createErrorHandler() {
  return (error, req, res, next) => {
    // Log error for debugging
    console.error('API Error:', error);
    
    // If headers are already sent, delegate to default error handler
    if (res.headersSent) {
      return next(error);
    }
    
    // Format error response
    const response = {
      error: error.name || 'Error',
      message: error.message || 'An error occurred',
      statusCode: error.statusCode || 500
    };
    
    // Add details if available
    if (error.details) {
      response.details = error.details;
    }
    
    // Add stack trace in development
    if (process.env.NODE_ENV === 'development') {
      response.stack = error.stack;
    }
    
    res.status(response.statusCode).json(response);
  };
}
 
// Export all error classes and utilities
export {
  ApiError,
  ValidationError,
  AuthenticationError,
  AuthorizationError,
  NotFoundError,
  ConflictError,
  withErrorHandling,
  createErrorHandler
};