#best way to handle errors in multiple api request in 1 function
1 messages · Page 1 of 1 (latest)
In Next.js, you can handle errors in multiple API requests within a single function using a try-catch block. This allows you to catch any errors that occur during the execution of the async operations and send an appropriate response back to the client.
Here's an example from the Next.js documentation (https://nextjs.org/docs/pages/building-your-application/routing/api-routes):
export default async function handler(req, res) {
try {
const result = await someAsyncOperation() // replace with your API request
res.status(200).json({ result })
} catch (err) {
res.status(500).json({ error: 'failed to load data' })
}
}
In this example, someAsyncOperation() represents your API request. If you have multiple API requests, you can use Promise.all() to execute them concurrently and wait for all to complete. If any of the promises reject, the error will be caught by the catch block.
export default async function handler(req, res) {
try {
const [result1, result2] = await Promise.all([apiRequest1(), apiRequest2()]) // replace with your API requests
res.status(200).json({ result1, result2 })
} catch (err) {
res.status(500).json({ error: 'failed to load data' })
}
}