API Error Handling
APIs should provide predictable error structures. Avoid returning raw database exceptions or stack traces to clients.
Differentiate client errors such as invalid input from authentication failures, authorization failures, missing resources, conflicts, and unexpected server failures.
A consistent error format makes frontend and external integrations easier to maintain.
Consistent API Error
return NextResponse.json(
{
error: {
code: 'RESOURCE_NOT_FOUND',
message: 'Product was not found'
}
},
{ status: 404 }
);💡 A stable error structure gives API consumers a predictable contract.
Key Takeaways
- Do not leak internal exceptions.
- Use meaningful status codes.
- Define a consistent error response contract.