-
Notifications
You must be signed in to change notification settings - Fork 0
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
Refactor your Nextjs code #111
Labels
Comments
Proper Error Message
class Error {
name: string;
message: string;
stack?: string;
constructor(message?: string) {
this.name = 'Error'; // Default error name
this.message = message || ''; // The error message you pass in
this.stack = (new Error()).stack; // The stack trace
}
}
// We're saying "APIError is like Error, but with extra stuff"
export default class APIError extends Error {
// The name property is special - it helps identify what kind of error this is
public readonly name: string = 'APIError';
constructor(
// message: what went wrong
message: string,
// statusCode: HTTP status code (like 404, 500, etc.)
public readonly statusCode: number = 500,
// details: any extra info we want to attach
public readonly details?: Record<string, unknown>
) {
// Call the parent (Error) constructor with our message
// This sets up the basic error stuff for us
super(message);
// This next line is a TypeScript quirk we need when extending built-in classes
// It makes sure our APIError behaves like a proper Error
Object.setPrototypeOf(this, APIError.prototype);
// This gives us a nice stack trace when something goes wrong
Error.captureStackTrace(this, APIError);
}
// This helps us convert our error to JSON if we need to send it somewhere
toJSON() {
return {
name: this.name,
message: this.message,
statusCode: this.statusCode,
details: this.details,
stack: this.stack
};
}
}
// Creating a basic API error
const simpleError = new APIError('User not found');
console.log(simpleError.message); // "User not found"
console.log(simpleError.statusCode); // 500 (default value)
// Creating a more detailed API error
const detailedError = new APIError(
'Invalid user data',
400, // Bad request status code
{ field: 'email', problem: 'invalid format' }
);
console.log(detailedError.message); // "Invalid user data"
console.log(detailedError.statusCode); // 400
console.log(detailedError.details); // { field: 'email', problem: 'invalid format' }
// And because it extends Error, this still works:
console.log(detailedError instanceof Error); // true
console.log(detailedError instanceof APIError); // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The text was updated successfully, but these errors were encountered: