Next.js - Error Handling



Error Handling in Next.js

Next.js provides a built-in error handling mechanism which will help developers to detect and handle errors in their applications. For example, if a user tries to access a page that does not exist, you can display a custom 404 error page according to your application theme. There are two types of errors that can occur in Next.js:

  • Expected Errors
  • Unexpected Errors

Expected errors can be handled easily by creating custom error handling pages. However, unexpected errors are harder to handle because they can occur at any point in the application lifecycle. To handle unexpected errors, you can use the useActionState hook to catch the error and return the error message to the client.

Create a Page to Handle Internal Server Error

Internal Server Error occur when the server is not able to process the request. In that case, Next.js will display a default error 500 page to that user, but you can create a customized 500 page according to your application theme. For this, create a file named 500.tsx in the /app directory.

// /app/500.tsx

export default function Custom500() {
    return (
        <div>
            <h1>500 - Server Error</h1>
            <p>Sorry, something went wrong on our server.</p>
        </div>
    );
  }

Output

To server error page, we have to trigger the error in our application. So we used 'getServerSideProps' with a thrown error in /500-test/index.tsx file.

500 error

Create a Custom 404 Error Page

The 404 error will be raised when user try to access a route that is not existing in our application. To handle this error you can create a custom 404 page.

// /app/404.tsx

export default function Custom404() {
    return (
        <div>
            <h1>404 - Page Not Found</h1>
            <p>Sorry, the page you are looking for does not exist.</p>
        </div>
    );
}

Output

In the Output, when we try to visit any random pages, 404 error which we defined is displayed.

404 error

Handling Unexpected Errors

Unexpected errors are those that can occur during the normal operation of the application, such as those from server-side form validation or failed requests. These errors should be handled explicitly and returned to the client.

To handle unexpected errors, you can use the useActionState , it will catch the error and return the error message to the client. It is recommended to avoid using try/catch blocks for expected errors. Instead, you can model expected errors as return values, not as thrown exceptions.

'use client'
 
import { useActionState } from 'react'
import { createPost } from '@/app/actions'
 
const initialState = {
  message: '',
}
 
export function Form() {
    // useActionState returns a state object
    const [state, formAction, pending] = useActionState(createPost, initialState)
 
  return (
    <form action={formAction}>
        <textarea id="content" name="content" required />
        {state?.message && <p>{state.message}</p>}

        <button disabled={pending}>Create Post</button>
    </form>
  )
}
Advertisements