Error logging helps you find and fix problems in your Next.js app quickly. It keeps track of what went wrong so you can improve your app.
Error logging strategies in NextJS
try { // code that might fail } catch (error) { console.error('Error message:', error); }
Use try...catch blocks to catch errors in your code.
console.error() prints error details to the terminal or browser console.
try { const data = await fetch('/api/data'); const json = await data.json(); } catch (error) { console.error('Failed to fetch data:', error); }
import { NextApiRequest, NextApiResponse } from 'next'; export default function handler(req, res) { try { // some code that may throw res.status(200).json({ message: 'Success' }); } catch (error) { console.error('API error:', error); res.status(500).json({ error: 'Internal Server Error' }); } }
if (process.env.NODE_ENV === 'production') { // send error to external service like Sentry Sentry.captureException(error); } else { console.error(error); }
This Next.js API route fetches data from an external API. If fetching fails, it logs the error and returns a 500 error response.
import { NextApiRequest, NextApiResponse } from 'next'; export default async function handler(req, res) { try { const response = await fetch('https://jsonplaceholder.typicode.com/posts/1'); if (!response.ok) { throw new Error('Network response was not ok'); } const data = await response.json(); res.status(200).json(data); } catch (error) { console.error('Fetch error:', error); res.status(500).json({ error: 'Failed to load data' }); } }
Always log enough details to understand the error but avoid sensitive data.
Use external error tracking tools like Sentry or LogRocket for production apps.
Console logs are helpful during development but may be removed or redirected in production.
Error logging helps find and fix problems fast.
Use try...catch and console.error() to log errors.
Consider external services for better error tracking in production.
Practice
Solution
Step 1: Understand error logging purpose
Error logging is used to catch errors that happen during app execution.Step 2: Identify why errors are logged
Logging errors helps developers find and fix problems to improve app stability.Final Answer:
To catch and record errors for fixing issues later -> Option DQuick Check:
Error logging purpose = Catch and fix errors [OK]
- Confusing error logging with performance optimization
- Thinking error logging improves SEO
- Believing error logging reduces app size
try...catch?Solution
Step 1: Review correct try...catch syntax
The correct syntax uses parentheses around the error variable in catch: catch (error).Step 2: Check logging method
console.error(error) correctly logs the error object to the console.Final Answer:
try { /* code */ } catch (error) { console.error(error) } -> Option BQuick Check:
Correct try...catch syntax = try { /* code */ } catch (error) { console.error(error) } [OK]
- Omitting parentheses in catch
- Using console.log instead of console.error
- Incorrect try or catch block syntax
try {
throw new Error('Failed to fetch data')
} catch (err) {
console.error('Error:', err.message)
}Solution
Step 1: Understand the thrown error
The code throws an Error object with message 'Failed to fetch data'.Step 2: Analyze the catch block output
console.error prints 'Error:' plus the error message, resulting in 'Error: Failed to fetch data'.Final Answer:
Error: Failed to fetch data -> Option AQuick Check:
console.error prints label + error message = Error: Failed to fetch data [OK]
- Confusing error object with error message string
- Expecting double 'Error:' prefix
- Ignoring the label string in console.error
try {
const data = await fetchData()
} catch {
console.error(error)
}Solution
Step 1: Check catch block syntax
The catch block is missing the error parameter, so 'error' is undefined inside it.Step 2: Understand error usage
console.error(error) fails because 'error' is not declared; catch must declare it like catch (error).Final Answer:
Missing error parameter in catch block -> Option AQuick Check:
Catch needs error parameter to log it [OK]
- Omitting error parameter in catch
- Thinking console.error is wrong here
- Misunderstanding async/await usage
Solution
Step 1: Understand production error logging needs
In production, errors should be tracked centrally to fix issues quickly.Step 2: Identify best practice
Sending errors to external services (like Sentry) plus local logging helps monitor and debug effectively.Final Answer:
Send errors to an external monitoring service and log locally -> Option CQuick Check:
Production error tracking = external service + local logs [OK]
- Ignoring production error tracking
- Disabling logging to save performance
- Logging only in browser without server monitoring
Ready to prove it?
Pass the test and this pattern moves unknown
