Performance: Server-side error handling
This affects server response time and user experience by controlling how quickly errors are detected and communicated to the client.
Jump into concepts and practice - no test required
export default async function handler(req, res) { try { const data = await fetchData(); res.status(200).json(data); } catch (error) { console.error(error); res.status(500).json({ error: 'Internal Server Error' }); } }
export default async function handler(req, res) { try { const data = await fetchData(); res.status(200).json(data); } catch (error) { // No early return or proper status code console.error(error); res.end(); } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No error handling or improper response | N/A (server-side) | N/A | Delays initial paint | [X] Bad |
| Proper try/catch with immediate error response | N/A (server-side) | N/A | Faster initial paint with fallback UI | [OK] Good |
try...catch blocks in Next.js server-side functions?try...catch helps catch these errors.try...catchtry block runs code that might fail, and the catch block handles errors to prevent crashes and provide feedback.try { ... } catch (error) { ... } to catch errors.export async function GET() {
try {
throw new Error('Failed to fetch data');
} catch (error) {
return new Response(error.message, { status: 500 });
}
}export async function GET() {
try {
const data = await fetch('https://api.example.com/data');
return new Response(JSON.stringify(data));
} catch (error) {
return new Response('Error occurred', { status: 500 });
}
}response.json() to parse it.res.ok and handles 404 with a specific response, throwing errors for other failures.