javascript / beginner
Snippet
Safely Loading Product Details with Promise Catch Handler
Promises represent the eventual completion or failure of an asynchronous operation. Using the .catch() method allows you to catch any network errors or custom thrown exceptions that occur in the promise chain, preventing unhandled promise rejections and allowing the component state to reflect errors to the user.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<script setup>import { ref, onMounted } from 'vue';const product = ref(null);const errorMessage = ref('');const loadProduct = (id) => {fetch(`/api/products/${id}`).then(response => {if (!response.ok) {throw new Error('Product not found');}return response.json();}).then(data => {product.value = data;}).catch(error => {errorMessage.value = error.message;});};onMounted(() => loadProduct(42));</script>
vue
Breakdown
1
if (!response.ok) { throw new Error('Product not found'); }
Explicitly throws an Error instance if the HTTP status indicates failure.
2
.catch(error => { errorMessage.value = error.message; });
Catches any error in the fetch chain and assigns its message to a reactive error state.