Skip to content

Instantly share code, notes, and snippets.

@SpenceDiNicolantonio
Created May 3, 2024 02:41
Show Gist options
  • Save SpenceDiNicolantonio/66b3c7f0ab12b32b850b86f5043d2114 to your computer and use it in GitHub Desktop.
Save SpenceDiNicolantonio/66b3c7f0ab12b32b850b86f5043d2114 to your computer and use it in GitHub Desktop.
Typescript error logger #typescript
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