Skip to content
Algol Blog

How I Handle Errors in Next.js Cleanly & User-Friendly

nextjs, error-handling, typescript, web-dev2 min read

error-handling-nextjs-2026

How I Handle Errors in Next.js Cleanly & User-Friendly (2026)

Hey everyone,

Error handling is often treated as an afterthought, but it's actually one of the things that most frustrates users and gives developers a headache when debugging.

After working on several projects, I've landed on a pretty consistent approach. Here's what I use now:

1. Separate Errors by Layer

I split errors into 3 types:

  • Validation Error → from Zod / forms (400)
  • Business Logic Error → e.g. "user doesn't have access" or "insufficient balance"
  • Unexpected Error → system / database / network errors

2. Custom Error Class

I create my own class to keep things clear:

export class AppError extends Error {
constructor(
public message: string,
public statusCode: number = 400,
public code?: string,
) {
super(message);
}
}

3. Error Handling in Server Actions

"use server";
export async function createInvoice(data: FormData) {
try {
// validation + business logic
} catch (error) {
if (error instanceof AppError) {
return { error: error.message };
}
console.error(error);
return { error: "Something went wrong. Please try again." };
}
}

4. Good Error UI

  • Use error.tsx in the App Router for unexpected errors
  • Show a user-friendly message (don't expose the stack trace)
  • Provide a clear "Try again" button or redirect

5. Useful Logging

I log errors to a service like Sentry or Axiom, complete with context (user id, action name, etc.). This helps a lot when debugging in production.

The Principles I Stick To

  1. Never let an error "leak" to the user in a technical form
  2. Always give actionable feedback
  3. Log the details on the server, keep it simple on the client
  4. Consistency matters more than perfection

Conclusion

Good error handling isn't just about try-catch. It's about communication — with the user, and with yourself when debugging.

If error handling in your project still feels messy, try starting with a custom error class and a consistent return type first.


A question for you all: How do you handle errors in Next.js these days? Do you use a specific library, or go fully custom?

Share your thoughts in the comments!

— Ady Rahmansyah Software Engineer | Tech Blogger | Coffee Addict

© 2026 by Algol Blog. All rights reserved.
Theme by LekoArts