Blog>
Snippets

Handling Errors in API Routes

Show a concrete example of error handling in an API route in Next.js, using try/catch blocks to catch errors and send appropriate HTTP responses.
export default async function handler(req, res) {
  try {
    // ... your API logic here
    // e.g., fetching data from a database

    // Optionally, you can use res.status(200).json({ data: 'Success' })
    // to send a successful response with a status code of 200
    res.status(200).json({ data: 'Success' });
  } catch (error) {
    // Log the error for server monitoring
    console.error('API Error:', error);

    // Send an error status code along with the error message
    // You might want to hide error details in production
    res.status(500).json({ error: 'Internal Server Error' });
  }
}
This Next.js API route function handles errors gracefully. Within a try block, the API logic is executed, such as fetching data from a database. If an error occurs within this block, the catch block is executed. The error is logged to the console for debugging purposes. Finally, a generic 'Internal Server Error' message is sent back to the client with a status code of 500, which indicates a server-side error.
import { useState } from 'react';

function MyComponent() {
  const [error, setError] = useState(null);

  async function fetchData() {
    try {
      const response = await fetch('/api/myendpoint');
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const data = await response.json();
      // Handle the data from the response
    } catch (e) {
      setError(e.message);
    }
  }

  return (
    <div>
      {error ? <p>Error: {error}</p> : <p>Fetch data by clicking the button</p>}
      <button onClick={fetchData}>Fetch Data</button>
    </div>
  );
}
Here is a React functional component using Next.js that utilizes the useState hook to handle errors on the client side as a result of fetching data from an API endpoint. In the fetchData function, an API call is made using the fetch method. If the response is not OK (i.e., the status code is not in the range 200-299), it throws an error. The catch block then sets the error message in the component's state, which is displayed to the user. A button triggers fetchData to initiate the API call.