Created
May 3, 2024 02:41
-
-
Save SpenceDiNicolantonio/66b3c7f0ab12b32b850b86f5043d2114 to your computer and use it in GitHub Desktop.
Typescript error logger #typescript
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
export function logError(err: unknown, context?: string) { | |
// Convert to Error if it's not one | |
let error: Error; | |
if (err instanceof Error) { | |
error = err; | |
} else { | |
// Wrap string in Error, but pop first line of stack (which will be this line) | |
error = new Error(String(err)); | |
error.stack = error.stack?.split('\n').slice(1).join('\n'); | |
} | |
const contextString = context ? ` (${context})` : ''; | |
const stackString = error.stack ? error.stack.split('\n').slice(1).join('\n') : ''; | |
const errorData = Object.keys(error).length ? { ...error } : ''; | |
console.error(`${error.name}: ${error.message}${contextString}\n${stackString}`, errorData); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment