Created
October 25, 2024 14:49
-
-
Save muhdkhokhar/a1963fe2105213e6a237798161ed9ee5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
@Injectable({ | |
providedIn: 'root', | |
}) | |
export class ConsoleInterceptorService { | |
private isHandlingError = false; | |
constructor() { | |
this.overrideConsoleError(); | |
} | |
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; | |
// Extract information from the stack trace. | |
const errorInfo = this.extractErrorInfo(errorStack); | |
// Log the error information and the intercepted error. | |
this.logError(args, errorInfo); | |
// Call the original console.error | |
originalConsoleError.apply(console, args); | |
this.isHandlingError = false; | |
} else { | |
originalConsoleError.apply(console, args); | |
} | |
}; | |
} | |
private extractErrorInfo(stack?: string): string { | |
if (!stack) return 'No stack trace available'; | |
// Split the stack into lines | |
const stackLines = stack.split('\n'); | |
// The 3rd line typically contains the caller information. | |
// The first line is 'Error', and the second is the line calling new Error(). | |
const callerLine = stackLines[2]; | |
// Extract relevant information (this may vary between browsers) | |
const match = callerLine.match(/at\s+(.*)\s+\((.*):(\d+):(\d+)\)/) || callerLine.match(/at\s+(.*):(\d+):(\d+)/); | |
if (match) { | |
const method = match[1]; | |
const file = match[2]; | |
const line = match[3]; | |
return `Method: ${method}, File: ${file}, Line: ${line}`; | |
} | |
return 'Caller information not available'; | |
} | |
private logError(args: any[], errorInfo: string): void { | |
// Implement your custom error handling logic here, e.g., send to a logging service | |
console.log('Intercepted error:', args, 'Error info:', errorInfo); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment