Async Error Handling Patterns
This note is for patterns that handle errors in asynchronous JavaScript.
try…catch With async/await
async function loadData(){
try {
const response = await fetch("/api/data");
if(!response.ok){
throw new Error("Request failed");
}
const data = await response.json();
console.log(data);
}
catch(error){
console.error("Could not load data:", error);
}
}Pattern
- Put risky async code inside
try. - Check
response.okmanually. - Throw an error when the response is not valid.
- Handle the error in
catch.
Why This Matters
fetch() only rejects on network failure. A 404 or 500 response still needs to be checked with response.ok.