0 day streak
javascript / beginner
Snippet

Catching Async Data Fetching Errors with Try-Catch Blocks

Using try-catch blocks in async functions ensures network or server failures are caught gracefully without crashing your Next.js Server Components.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
// app/data/page.js
export async function getProductData(id) {
try {
const response = await fetch(`https://api.example.com/items/${id}`);
if (!response.ok) throw new Error('Network response failed');
return await response.json();
} catch (error) {
return { error: error.message };
}
}
nextjs
Breakdown
1
export async function getProductData(id) {
Declares an asynchronous function designed for server data fetching.
2
try {
Starts a protective try block to enclose potentially failing async network operations.
3
const response = await fetch(`https://api.example.com/items/${id}`);
Awaits the asynchronous HTTP request response from the remote server.
4
if (!response.ok) throw new Error('Network response failed');
Checks if response status is outside 200-299 range and throws an error if so.
5
} catch (error) {
Catches any runtime or network exception thrown within the try block.
6
return { error: error.message };
Returns a safe error object fallback instead of crashing the execution flow.