Spaces:
Sleeping
Sleeping
File size: 8,201 Bytes
2a889d3 | 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 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 | import { NextRequest, NextResponse } from 'next/server';
// Error types
export enum ErrorType {
VALIDATION_ERROR = 'VALIDATION_ERROR',
AUTHENTICATION_ERROR = 'AUTHENTICATION_ERROR',
AUTHORIZATION_ERROR = 'AUTHORIZATION_ERROR',
NOT_FOUND_ERROR = 'NOT_FOUND_ERROR',
DUPLICATE_ERROR = 'DUPLICATE_ERROR',
DATABASE_ERROR = 'DATABASE_ERROR',
RATE_LIMIT_ERROR = 'RATE_LIMIT_ERROR',
INTERNAL_ERROR = 'INTERNAL_ERROR'
}
// Custom error class
export class AppError extends Error {
public readonly type: ErrorType;
public readonly statusCode: number;
public readonly isOperational: boolean;
public readonly context?: any;
constructor(
message: string,
type: ErrorType,
statusCode: number = 500,
isOperational: boolean = true,
context?: any
) {
super(message);
this.type = type;
this.statusCode = statusCode;
this.isOperational = isOperational;
this.context = context;
Error.captureStackTrace(this, this.constructor);
}
}
// Logger utility
export class Logger {
private static log(level: string, message: string, meta?: any) {
const timestamp = new Date().toISOString();
const logEntry = {
timestamp,
level,
message,
meta,
environment: process.env.NODE_ENV || 'development'
};
// In production, send to logging service
if (process.env.NODE_ENV === 'production') {
console.log(JSON.stringify(logEntry));
} else {
console.log(`[${timestamp}] ${level.toUpperCase()}: ${message}`);
if (meta) console.log('Meta:', meta);
}
}
static info(message: string, meta?: any) {
this.log('info', message, meta);
}
static warn(message: string, meta?: any) {
this.log('warn', message, meta);
}
static error(message: string, error?: Error | any, meta?: any) {
this.log('error', message, {
error: error?.message || error,
stack: error?.stack,
...meta
});
}
static debug(message: string, meta?: any) {
if (process.env.NODE_ENV === 'development') {
this.log('debug', message, meta);
}
}
static security(message: string, meta?: any) {
this.log('security', message, {
...meta,
timestamp: new Date().toISOString(),
ip: meta?.ip || 'unknown',
userAgent: meta?.userAgent || 'unknown'
});
}
}
// Audit logging for data changes
export class AuditLogger {
static log(
action: string,
entity: string,
entityId: string,
userId: string,
changes?: any,
meta?: any
) {
const auditEntry = {
timestamp: new Date().toISOString(),
action,
entity,
entityId,
userId,
changes,
meta,
environment: process.env.NODE_ENV || 'development'
};
Logger.info(`AUDIT: ${action} on ${entity} ${entityId}`, auditEntry);
// In production, store in secure audit database
if (process.env.NODE_ENV === 'production') {
// TODO: Implement secure audit log storage
}
}
static logSecurity(
eventType: string,
identifier: string,
details?: any
) {
const securityEntry = {
timestamp: new Date().toISOString(),
eventType,
identifier,
details,
environment: process.env.NODE_ENV || 'development'
};
Logger.security(`SECURITY: ${eventType} from ${identifier}`, securityEntry);
// In production, store in secure security log database
if (process.env.NODE_ENV === 'production') {
// TODO: Implement secure security log storage
}
}
}
// Error handler middleware
export function handleApiError(error: any, request?: NextRequest): NextResponse {
Logger.error('API Error occurred', error, {
url: request?.url,
method: request?.method,
userAgent: request?.headers.get('user-agent'),
ip: request?.headers.get('x-forwarded-for') || request?.headers.get('x-real-ip')
});
// Handle validation errors
if (error.type === ErrorType.VALIDATION_ERROR) {
return NextResponse.json(
{
success: false,
error: 'Validation Error',
message: error.message,
details: error.context?.errors || []
},
{ status: 400 }
);
}
// Handle authentication errors
if (error.type === ErrorType.AUTHENTICATION_ERROR) {
Logger.security('Authentication failed', {
url: request?.url,
userAgent: request?.headers.get('user-agent')
});
return NextResponse.json(
{
success: false,
error: 'Authentication Error',
message: 'Please provide valid authentication credentials'
},
{ status: 401 }
);
}
// Handle authorization errors
if (error.type === ErrorType.AUTHORIZATION_ERROR) {
Logger.security('Authorization failed', {
url: request?.url,
userAgent: request?.headers.get('user-agent')
});
return NextResponse.json(
{
success: false,
error: 'Authorization Error',
message: 'You do not have permission to perform this action'
},
{ status: 403 }
);
}
// Handle not found errors
if (error.type === ErrorType.NOT_FOUND_ERROR) {
return NextResponse.json(
{
success: false,
error: 'Not Found',
message: error.message
},
{ status: 404 }
);
}
// Handle duplicate errors
if (error.type === ErrorType.DUPLICATE_ERROR) {
return NextResponse.json(
{
success: false,
error: 'Duplicate Entry',
message: error.message
},
{ status: 409 }
);
}
// Handle rate limit errors
if (error.type === ErrorType.RATE_LIMIT_ERROR) {
return NextResponse.json(
{
success: false,
error: 'Rate Limit Exceeded',
message: 'Too many requests. Please try again later.'
},
{ status: 429 }
);
}
// Handle database errors
if (error.type === ErrorType.DATABASE_ERROR) {
Logger.error('Database error occurred', error);
return NextResponse.json(
{
success: false,
error: 'Database Error',
message: 'An error occurred while processing your request'
},
{ status: 500 }
);
}
// Handle all other errors
const isDevelopment = process.env.NODE_ENV === 'development';
return NextResponse.json(
{
success: false,
error: 'Internal Server Error',
message: isDevelopment ? error.message : 'An unexpected error occurred',
...(isDevelopment && { stack: error.stack, context: error.context })
},
{ status: error.statusCode || 500 }
);
}
// Validation error helper
export function createValidationError(errors: string[], context?: any): AppError {
return new AppError(
'Validation failed',
ErrorType.VALIDATION_ERROR,
400,
true,
{ errors, ...context }
);
}
// Authentication error helper
export function createAuthenticationError(message: string = 'Authentication required'): AppError {
return new AppError(message, ErrorType.AUTHENTICATION_ERROR, 401);
}
// Authorization error helper
export function createAuthorizationError(message: string = 'Insufficient permissions'): AppError {
return new AppError(message, ErrorType.AUTHORIZATION_ERROR, 403);
}
// Not found error helper
export function createNotFoundError(entity: string, id?: string): AppError {
const message = id ? `${entity} with id ${id} not found` : `${entity} not found`;
return new AppError(message, ErrorType.NOT_FOUND_ERROR, 404);
}
// Duplicate error helper
export function createDuplicateError(entity: string, field: string, value: string): AppError {
return new AppError(
`${entity} with ${field} '${value}' already exists`,
ErrorType.DUPLICATE_ERROR,
409
);
}
// Database error helper
export function createDatabaseError(message: string, originalError?: any): AppError {
return new AppError(
message,
ErrorType.DATABASE_ERROR,
500,
true,
{ originalError: originalError?.message }
);
}
// Rate limit error helper
export function createRateLimitError(limit: number, windowMs: number): AppError {
return new AppError(
`Rate limit exceeded. Maximum ${limit} requests per ${windowMs}ms allowed.`,
ErrorType.RATE_LIMIT_ERROR,
429
);
}
|