0
0
Vueframework~10 mins

Error handling in HTTP calls in Vue - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Error handling in HTTP calls
Start HTTP call
Send request
Wait for response
Response received?
NoCatch error
Set error state
Check status code
Set error state
Yes
Process data
Update UI with data
End
This flow shows how a Vue app sends an HTTP request, waits for the response, handles errors if any, and updates the UI accordingly.
Execution Sample
Vue
import { ref } from 'vue';

const data = ref(null);
const error = ref(null);

async function fetchData() {
  try {
    const res = await fetch('https://api.example.com/data');
    if (!res.ok) throw new Error('Network response was not ok');
    data.value = await res.json();
    error.value = null;
  } catch (err) {
    error.value = err.message;
    data.value = null;
  }
}
This Vue code fetches data from an API, sets the data if successful, or sets an error message if something goes wrong.
Execution Table
StepActionHTTP ResponseConditionState ChangeUI Update
1Call fetchData()N/AN/Adata=null, error=nullShow loading or empty
2Send fetch requestPendingN/ANo change yetShow loading
3Receive responseStatus 200 OKres.ok is truePrepare to parse JSONNo change yet
4Parse JSON dataValid JSONN/Adata set to parsed JSONUI shows data
5Clear errorN/AN/Aerror set to nullRemove error messages
6End fetchData()N/AN/AFinal state: data with value, error nullUI updated with data
7Call fetchData() againN/AN/AReset statesShow loading
8Send fetch requestPendingN/ANo change yetShow loading
9Receive responseStatus 500 Errorres.ok is falseThrow errorNo data update
10Catch errorError thrownCatch block runserror set to message, data nullShow error message
11End fetchData()N/AN/AFinal state: data null, error setUI shows error
💡 Execution stops after setting data or error based on response success or failure.
Variable Tracker
VariableStartAfter Step 4After Step 5After Step 10Final
datanullparsed JSON objectparsed JSON objectnullnull or parsed JSON
errornullnullnull'Network response was not ok''Network response was not ok' or null
Key Moments - 3 Insights
Why do we check if res.ok is false before parsing JSON?
Because a response can be received but still be an error (like 404 or 500). Checking res.ok ensures we only parse JSON if the response is successful, as shown in execution_table row 3 and 9.
What happens if fetch itself fails (like no internet)?
The catch block runs, setting the error message and clearing data, as seen in execution_table row 10.
Why do we reset error to null on successful fetch?
To clear any previous errors so the UI shows fresh data without old error messages, as in execution_table row 5.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'error' after step 5?
Anull
B'Network response was not ok'
Cundefined
Dparsed JSON object
💡 Hint
Check the 'State Change' column at step 5 where error is set to null.
At which step does the code detect a failed HTTP response?
AStep 4
BStep 9
CStep 3
DStep 10
💡 Hint
Look for the step where res.ok is false and an error is thrown (step 9).
If the fetch call fails due to no internet, which step shows the error being handled?
AStep 8
BStep 9
CStep 10
DStep 11
💡 Hint
The catch block runs on fetch failure, shown at step 10.
Concept Snapshot
Error handling in HTTP calls in Vue:
- Use async/await with try/catch
- Check response.ok before parsing JSON
- Set data on success, error message on failure
- Reset error on new successful fetch
- Update UI reactively based on data/error state
Full Transcript
This visual execution shows how Vue handles errors during HTTP calls. First, the fetchData function sends a request and waits for a response. If the response is successful (res.ok true), it parses JSON and updates the data variable, clearing any previous error. If the response is an error (res.ok false) or the fetch fails (network error), the catch block sets an error message and clears data. The UI updates reactively to show data or error messages accordingly. Key moments include checking res.ok before parsing, handling fetch failures, and resetting error state on success.