-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Enhance Error Handling with Custom Error Types #329
Comments
@coderabbitai run an analysis to check error handling integrity and see for opportunities of adding this Error Handling System. |
Tip For best results, initiate chat on the files or code changes. Let me analyze the error handling patterns found in the codebase and provide recommendations for implementing a custom error handling system. @AndlerRL Based on the analysis, here are the key findings and recommendations:
// Base error class
export class MasterBotsError extends Error {
constructor(message: string, public code: string) {
super(message);
this.name = this.constructor.name;
}
}
// Authentication/Authorization errors
export class AuthError extends MasterBotsError {
constructor(message: string) {
super(message, 'AUTH_ERROR');
}
}
// Environment configuration errors
export class ConfigError extends MasterBotsError {
constructor(message: string) {
super(message, 'CONFIG_ERROR');
}
}
// JWT related errors
export class JWTError extends MasterBotsError {
constructor(message: string) {
super(message, 'JWT_ERROR');
}
}
// AI/Model related errors
export class AIError extends MasterBotsError {
constructor(message: string) {
super(message, 'AI_ERROR');
}
}
// GraphQL/API errors
export class APIError extends MasterBotsError {
constructor(message: string) {
super(message, 'API_ERROR');
}
}
Replace current error throws with custom errors. Examples: // Before:
if (!session) {
throw new Error('Unauthorized: No user session found');
}
// After:
if (!session) {
throw new AuthError('No user session found');
}
// Before:
if (!process.env.NEXT_PUBLIC_APP_ENV) {
throw new Error("NEXT_PUBLIC_APP_ENV is not set");
}
// After:
if (!process.env.NEXT_PUBLIC_APP_ENV) {
throw new ConfigError("NEXT_PUBLIC_APP_ENV is not set");
}
// Before:
throw new Error("Invalid token");
// After:
throw new JWTError("Invalid token");
export function errorHandler(error: Error) {
if (error instanceof MasterBotsError) {
// Handle known errors
console.error(`[${error.code}] ${error.message}`);
// Add appropriate error reporting/logging
return {
code: error.code,
message: error.message
};
}
// Handle unknown errors
console.error('[UNKNOWN_ERROR]', error);
return {
code: 'UNKNOWN_ERROR',
message: 'An unexpected error occurred'
};
}
Would you like me to create a GitHub issue to track this implementation? I can include the detailed steps and code examples. 🔗 Analysis chainI'll help analyze the error handling integrity across the codebase. Let me search for error handling patterns and potential areas for improvement. 🏁 Scripts executedThe following scripts were executed for the analysis: Script:
Length of output: 66957 ✏️ Learnings added
|
Tip For best results, initiate chat on the files or code changes. @AndlerRL Based on the analysis of the codebase, I've identified several areas where error handling can be improved. Here's a detailed breakdown:
a. API Routes ( // Current pattern
catch (error) {
console.error('Error in chat API route:', error)
return NextResponse.json(
{ error: 'An error occurred while processing your request' },
{ status: 500 }
)
}
// Should be improved to:
catch (error) {
if (error instanceof APIError) {
return NextResponse.json(
{
code: error.code,
message: error.message,
details: error.details
},
{ status: error.statusCode }
)
}
// Log and return a sanitized error for unexpected errors
logger.error('Unexpected error in chat API', { error })
return NextResponse.json(
{
code: 'INTERNAL_SERVER_ERROR',
message: 'An unexpected error occurred'
},
{ status: 500 }
)
} b. Authentication ( // Current pattern
console.error('User authentication failed: Invalid password')
throw new Error('Invalid credentials')
// Should be improved to:
throw new AuthError(
'AUTH.INVALID_CREDENTIALS',
'Invalid email or password provided',
401,
{ email }
) c. Payment Processing ( // Current pattern
console.error('Error creating subscription:', error)
return new Response(JSON.stringify({ error: stripeError?.message }))
// Should be improved to:
throw new PaymentError(
'PAYMENT.SUBSCRIPTION_FAILED',
'Failed to create subscription',
400,
{
stripeError: error.raw,
customerId,
planId
}
)
// src/errors/types.ts
export type ErrorCode =
| 'AUTH.INVALID_CREDENTIALS'
| 'AUTH.TOKEN_EXPIRED'
| 'PAYMENT.SUBSCRIPTION_FAILED'
| 'PAYMENT.INVALID_CARD'
| 'API.REQUEST_FAILED'
| 'API.VALIDATION_FAILED'
| 'CHAT.MESSAGE_FAILED'
| 'CHAT.THREAD_NOT_FOUND'
// ... more error codes
// src/errors/base.error.ts
export class BaseError extends Error {
constructor(
public code: ErrorCode,
message: string,
public statusCode: number = 500,
public details?: Record<string, unknown>
) {
super(message)
this.name = this.constructor.name
Error.captureStackTrace(this, this.constructor)
}
toJSON() {
return {
code: this.code,
message: this.message,
statusCode: this.statusCode,
details: this.details
}
}
}
// src/errors/auth.error.ts
export class AuthError extends BaseError {
constructor(
code: ErrorCode,
message: string,
statusCode = 401,
details?: Record<string, unknown>
) {
super(code, message, statusCode, details)
}
}
// src/errors/payment.error.ts
export class PaymentError extends BaseError {
constructor(
code: ErrorCode,
message: string,
statusCode = 400,
details?: Record<string, unknown>
) {
super(code, message, statusCode, details)
}
}
// src/errors/api.error.ts
export class APIError extends BaseError {
constructor(
code: ErrorCode,
message: string,
statusCode = 500,
details?: Record<string, unknown>
) {
super(code, message, statusCode, details)
}
}
Would you like me to create a GitHub issue to track the implementation of this error handling system with these specific recommendations? 🔗 Analysis chainI'll help analyze the error handling patterns in the codebase to identify opportunities for implementing a custom error handling system. Let me gather the necessary information. Let me analyze the results and provide a comprehensive review of error handling patterns and opportunities for improvement. Based on the gathered information, I'll provide a detailed analysis and recommendations for implementing a custom error handling system. @AndlerRL After analyzing the codebase, here's a comprehensive review of the current error handling patterns and recommendations for implementing a robust error handling system:
// src/errors/base.error.ts
export class BaseError extends Error {
constructor(
public code: string,
message: string,
public statusCode: number = 500,
public details?: unknown
) {
super(message);
this.name = this.constructor.name;
Error.captureStackTrace(this, this.constructor);
}
}
// src/errors/api.error.ts
export class APIError extends BaseError {
constructor(
code: string,
message: string,
statusCode: number = 500,
details?: unknown
) {
super(code, message, statusCode, details);
}
}
// src/errors/validation.error.ts
export class ValidationError extends BaseError {
constructor(message: string, details?: unknown) {
super('VALIDATION_ERROR', message, 400, details);
}
}
// src/errors/network.error.ts
export class NetworkError extends BaseError {
constructor(message: string, details?: unknown) {
super('NETWORK_ERROR', message, 503, details);
}
}
// src/errors/index.ts
export const ErrorCodes = {
VALIDATION: {
INVALID_INPUT: 'VALIDATION.INVALID_INPUT',
MISSING_REQUIRED: 'VALIDATION.MISSING_REQUIRED',
},
API: {
REQUEST_FAILED: 'API.REQUEST_FAILED',
RESPONSE_PARSING: 'API.RESPONSE_PARSING',
},
NETWORK: {
CONNECTION_FAILED: 'NETWORK.CONNECTION_FAILED',
TIMEOUT: 'NETWORK.TIMEOUT',
},
} as const;
export * from './base.error';
export * from './api.error';
export * from './validation.error';
export * from './network.error';
Here are the key areas where we should implement the new error handling system: a. API Calls: try {
const response = await fetch(url);
if (!response.ok) {
throw new APIError(
ErrorCodes.API.REQUEST_FAILED,
`API request failed: ${response.statusText}`,
response.status,
{ url, method: 'GET' }
);
}
} catch (error) {
if (error instanceof APIError) {
// Handle API specific errors
logger.error(error);
} else {
// Handle unexpected errors
throw new NetworkError(
`Unexpected error during API call: ${error.message}`,
{ originalError: error }
);
}
} b. Input Validation: function validateInput(data: unknown): void {
if (!data) {
throw new ValidationError(
'Data is required',
{ code: ErrorCodes.VALIDATION.MISSING_REQUIRED }
);
}
// More validation...
}
Would you like me to create a GitHub issue to track the implementation of this error handling system? I can include these recommendations and implementation steps in the issue for better tracking. 🏁 Scripts executedThe following scripts were executed for the analysis: Script:
Length of output: 67081 Script:
Length of output: 29910 ✏️ Learnings added
|
As discussed in PR #316 and this comment by @AndlerRL, we need to improve error handling across the codebase by:
URLBuilderError
).This issue will serve to track the progress of enhancing error handling practices throughout the project.
The text was updated successfully, but these errors were encountered: