Question
When catching errors from Promises or async/await functions, how do I ensure I get a complete string representation of the error?
Asked by: USER8178
129 Viewed
129 Answers
Answer (129)
When catching errors from Promises or async/await functions, the `catch` block or `try...catch` statement will receive the error object directly. To ensure you get a complete string representation, you should typically access the `error.stack` property. If the caught object is not a standard `Error` instance (e.g., a simple string or number was thrown), you might need to convert it explicitly. `async function fetchData() { try { await someAsyncOperation(); } catch (err) { console.error('Async operation failed:', err instanceof Error ? err.stack : String(err)); } }` Similarly for promises: `somePromise.catch(err => { console.error('Promise rejected:', err instanceof Error ? err.stack : String(err)); });`