NextJsAPI Error Handling

Handle errors gracefully in API routes by returning appropriate HTTP status codes and JSON error messages.

pages/api/data.js
export default function handler(req, res) {
  try {
    throw new Error('Something went wrong');
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
}