How can you handle a promise rejection when using await?
sobes.tech AI
Answer from AI
When using await with a promise, errors (reject) can be handled in several ways:
-
try...catchconstruct: The most common and recommended method. It allows elegant catching of errors thrown during the resolution or rejection of a promise.async function fetchData() { try { const response = await fetch('https://api.example.com/data'); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); console.log(data); } catch (error) { console.error('Error fetching data:', error); // Additional error handling or user notification } } fetchData(); -
.catch()method afterawait: Less preferred but possible. The error will be handled in the.catch()callback if the promise is rejected.async function fetchData() { const response = await fetch('https://api.example.com/data') .catch(error => { console.error('Error during fetch:', error); // Handle fetch error throw error; // Re-throw error for further handling if needed }); if (response && !response.ok) { console.error(`HTTP error! status: ${response.status}`); // Handle HTTP error } if (response && response.ok) { const data = await response.json() .catch(error => { console.error('Error parsing JSON:', error); // Handle JSON parsing error }); if (data) { console.log(data); } } } fetchData();This approach can become cumbersome when handling multiple potential failure points.
-
Error-return pattern: Some libraries or custom functions may return a tuple
[data, error]instead of rejecting the promise.async function safelyFetchData() { const [data, error] = await safePromise(fetch('https://api.example.com/data')); if (error) { console.error('General error fetching data:', error); return null; // Or another value indicating failure } // Assuming safePromise also handles response.ok console.log(data); return data; } // Example implementation of safePromise (simplified) async function safePromise(promise) { try { const result = await promise; // Might include check for result.ok for fetch if (result && result.ok !== undefined && !result.ok) { throw new Error(`HTTP error! status: ${result.status}`); } // For fetch, might need to await result.json() if (result && typeof result.json === 'function') { const jsonData = await result.json(); return [jsonData, null]; } return [result, null]; } catch (error) { return [null, error]; } } safelyFetchData();This pattern (often called "error-first callback" or "go-style error handling") is convenient when errors need to be handled locally without interrupting the function execution.
The cleanest and most readable way is to use try...catch around the block of code containing await.