/ opencodehub / src / lib / errors.ts
swadhinbiswas feat: implement production-grade security and fix critical vulnerabilities · 1/1/2026
0c17327
203 lines · 5.2 KB
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
/**
 * Unified Error Handling
 * Standardized error types and handlers for consistent API responses
 */

import { logger } from "@/lib/logger";

// Error codes for API responses
export type ErrorCode =
    | "UNAUTHORIZED"
    | "FORBIDDEN"
    | "NOT_FOUND"
    | "BAD_REQUEST"
    | "VALIDATION_ERROR"
    | "CONFLICT"
    | "RATE_LIMITED"
    | "INTERNAL_ERROR"
    | "SERVICE_UNAVAILABLE"
    | "GIT_ERROR"
    | "DATABASE_ERROR";

// HTTP status codes mapping
const STATUS_CODES: Record<ErrorCode, number> = {
    UNAUTHORIZED: 401,
    FORBIDDEN: 403,
    NOT_FOUND: 404,
    BAD_REQUEST: 400,
    VALIDATION_ERROR: 422,
    CONFLICT: 409,
    RATE_LIMITED: 429,
    INTERNAL_ERROR: 500,
    SERVICE_UNAVAILABLE: 503,
    GIT_ERROR: 500,
    DATABASE_ERROR: 500,
};

/**
 * Application Error class for consistent error handling
 */
export class AppError extends Error {
    public readonly code: ErrorCode;
    public readonly statusCode: number;
    public readonly details?: Record<string, unknown>;
    public readonly isOperational: boolean;

    constructor(
        code: ErrorCode,
        message: string,
        details?: Record<string, unknown>,
        isOperational = true
    ) {
        super(message);
        this.name = "AppError";
        this.code = code;
        this.statusCode = STATUS_CODES[code];
        this.details = details;
        this.isOperational = isOperational;

        // Capture stack trace
        Error.captureStackTrace(this, this.constructor);
    }

    /**
     * Convert to JSON response format
     */
    toJSON() {
        return {
            error: {
                code: this.code,
                message: this.message,
                ...(this.details && { details: this.details }),
            },
        };
    }

    /**
     * Convert to Response object
     */
    toResponse(): Response {
        return new Response(JSON.stringify(this.toJSON()), {
            status: this.statusCode,
            headers: { "Content-Type": "application/json" },
        });
    }
}

// Convenience factory functions
export const Errors = {
    unauthorized: (message = "Authentication required") =>
        new AppError("UNAUTHORIZED", message),

    forbidden: (message = "Access denied") =>
        new AppError("FORBIDDEN", message),

    notFound: (resource = "Resource") =>
        new AppError("NOT_FOUND", `${resource} not found`),

    badRequest: (message: string, details?: Record<string, unknown>) =>
        new AppError("BAD_REQUEST", message, details),

    validation: (errors: Record<string, string[]>) =>
        new AppError("VALIDATION_ERROR", "Validation failed", { errors }),

    conflict: (message: string) =>
        new AppError("CONFLICT", message),

    rateLimited: (retryAfter?: number) =>
        new AppError("RATE_LIMITED", "Too many requests", { retryAfter }),

    internal: (message = "Internal server error") =>
        new AppError("INTERNAL_ERROR", message, undefined, false),

    gitError: (message: string, details?: Record<string, unknown>) =>
        new AppError("GIT_ERROR", message, details),

    dbError: (message = "Database error") =>
        new AppError("DATABASE_ERROR", message, undefined, false),
};

/**
 * Wrap async API handlers with error handling
 */
export function withErrorHandler<T extends (...args: any[]) => Promise<Response>>(
    handler: T
): T {
    return (async (...args: Parameters<T>) => {
        try {
            return await handler(...args);
        } catch (error) {
            return handleError(error);
        }
    }) as T;
}

/**
 * Central error handler
 */
export function handleError(error: unknown): Response {
    // Known application error
    if (error instanceof AppError) {
        if (!error.isOperational) {
            logger.error({ err: error, code: error.code }, "Non-operational error");
        }
        return error.toResponse();
    }

    // Zod validation error
    if (error && typeof error === "object" && "issues" in error) {
        const zodError = error as { issues: Array<{ path: string[]; message: string }> };
        const errors: Record<string, string[]> = {};
        for (const issue of zodError.issues) {
            const path = issue.path.join(".");
            if (!errors[path]) errors[path] = [];
            errors[path].push(issue.message);
        }
        return Errors.validation(errors).toResponse();
    }

    // Unknown error - log and return generic message
    logger.error({ err: error }, "Unhandled error");
    return Errors.internal().toResponse();
}

/**
 * Assert condition or throw AppError
 */
export function assert(
    condition: unknown,
    error: AppError
): asserts condition {
    if (!condition) {
        throw error;
    }
}

/**
 * Assert user is authenticated
 */
export function assertAuthenticated(
    user: unknown
): asserts user is { id: string; username: string } {
    if (!user) {
        throw Errors.unauthorized();
    }
}

/**
 * Try-catch wrapper that converts errors to AppError
 */
export async function tryCatch<T>(
    fn: () => Promise<T>,
    errorFactory: (err: unknown) => AppError = () => Errors.internal()
): Promise<T> {
    try {
        return await fn();
    } catch (error) {
        if (error instanceof AppError) {
            throw error;
        }
        throw errorFactory(error);
    }
}