Skip to content

Instantly share code, notes, and snippets.

@muhdkhokhar
Created October 25, 2024 15:17
Show Gist options
  • Save muhdkhokhar/fdd062d328b5839253d0c874862580d5 to your computer and use it in GitHub Desktop.
Save muhdkhokhar/fdd062d328b5839253d0c874862580d5 to your computer and use it in GitHub Desktop.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class ConsoleInterceptorService {
private isHandlingError = false;
constructor() {
this.overrideConsoleError();
this.setupGlobalErrorHandlers();
}
private overrideConsoleError(): void {
const originalConsoleError = console.error;
console.error = (...args: any[]): void => {
if (!this.isHandlingError) {
this.isHandlingError = true;
// Create a new Error object to capture the stack trace.
const errorStack = new Error().stack;
// Log the error information and the intercepted error.
this.logError(args, errorStack);
// Call the original console.error
originalConsoleError.apply(console, args);
this.isHandlingError = false;
} else {
originalConsoleError.apply(console, args);
}
};
}
private setupGlobalErrorHandlers(): void {
// Handle uncaught errors in synchronous code.
window.onerror = (message, source, lineno, colno, error) => {
const errorStack = error ? error.stack : `at ${source}:${lineno}:${colno}`;
this.logError([`Unhandled error: ${message}`], errorStack);
};
// Handle unhandled promise rejections.
window.addEventListener('unhandledrejection', (event) => {
const reason = event.reason instanceof Error ? event.reason.stack : JSON.stringify(event.reason);
this.logError(['Unhandled promise rejection:', reason]);
});
}
private logError(args: any[], errorStack?: string): void {
// Log the intercepted error arguments.
console.log('Intercepted error:', args);
// Log the stack trace line by line for better readability.
if (errorStack) {
console.log('Stack trace:');
errorStack.split('\n').forEach((line) => console.log(line.trim()));
} else {
console.log('No stack trace available');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment