error-handling
Error Handling
Quick Start
When handling errors:
- Never expose technical details to users
- Log errors server-side with context
- Provide user-friendly error messages
- Use appropriate HTTP status codes
- Implement error recovery when possible
Common Patterns
API Error Handling
import { NextRequest, NextResponse } from 'next/server';
export async function POST(request: NextRequest) {
try {
// Business logic
const result = await processRequest();
return NextResponse.json(result);
} catch (error) {
// Log error with context
console.error('API Error:', {
endpoint: '/api/example',
error: error.message,
stack: error.stack,
timestamp: new Date().toISOString(),
});
// Return user-friendly error
return NextResponse.json(
{ error: 'Ha ocurrido un error. Por favor, intenta nuevamente.' },
{ status: 500 }
);
}
}
Validation Errors
import { z } from 'zod';
const schema = z.object({
email: z.string().email(),
name: z.string().min(1),
});
try {
const data = schema.parse(requestBody);
} catch (error) {
if (error instanceof z.ZodError) {
return NextResponse.json(
{
error: 'Datos inválidos',
details: error.errors.map(e => ({
field: e.path.join('.'),
message: e.message,
}))
},
{ status: 400 }
);
}
}
Component Error Handling
'use client';
import { useState } from 'react';
function ProductCard({ product }: ProductCardProps) {
const [error, setError] = useState<string | null>(null);
const handleAddToCart = async () => {
try {
setError(null);
await addToCart(product.id);
} catch (error) {
setError('No se pudo agregar el producto al carrito');
console.error('Add to cart error:', error);
}
};
return (
<div>
{error && (
<div className="text-red-500 text-sm">{error}</div>
)}
<Button onClick={handleAddToCart}>Agregar</Button>
</div>
);
}
Error Boundary
'use client';
import { ErrorBoundary } from 'react-error-boundary';
function ErrorFallback({ error, resetErrorBoundary }) {
return (
<div role="alert" className="p-4 border border-red-300 rounded">
<h2>Algo salió mal</h2>
<p>{error.message}</p>
<Button onClick={resetErrorBoundary}>Intentar de nuevo</Button>
</div>
);
}
function App() {
return (
<ErrorBoundary FallbackComponent={ErrorFallback}>
<YourComponent />
</ErrorBoundary>
);
}
Error Types
- 400 Bad Request: Invalid input
- 401 Unauthorized: Not authenticated
- 403 Forbidden: Not authorized
- 404 Not Found: Resource doesn't exist
- 500 Internal Server Error: Server error
- 503 Service Unavailable: Service down
Best Practices
- Log errors with full context
- Never expose stack traces to users
- Provide actionable error messages
- Implement retry logic for transient errors
- Use error boundaries for React components
More from santiagoxor/pintureria-digital
postgres-best-practices
Postgres performance optimization guidelines from Supabase. Contains rules across 8 categories prioritized by impact. Use when writing SQL queries, designing schemas, implementing indexes, optimizing queries, reviewing database performance, configuring connection pooling, or working with Row-Level Security (RLS).
29testing-qa
Specialized skill for writing and maintaining tests including unit tests, integration tests, E2E tests with Playwright, and accessibility tests. Use when writing tests for new features, debugging failed tests, improving test coverage, or setting up E2E tests.
18build-start
Specialized skill for building and starting Next.js applications, handling build errors, verifying production builds, and managing development servers. Use when building the application, starting development servers, troubleshooting build issues, or verifying production readiness.
16supabase-mcp-db
Apply Supabase migrations and manage the database using the Supabase MCP (user-supabase-SantiagoXOR). Use when the user asks to apply migrations, run migrations with MCP, manage the DB with Supabase MCP, list migrations, execute SQL, or inspect schema.
15multitenant-development
Specialized skill for working with the multitenant system including tenant detection, data isolation, tenant-specific configuration, and RLS policies. Use when implementing multitenant features, creating APIs that handle multiple tenants, configuring tenant assets, or debugging data isolation issues.
15analytics-tracking
Specialized skill for implementing and maintaining the analytics system including event tracking, e-commerce metrics, GA4 integration, and admin dashboard. Use when implementing tracking, creating custom metrics, integrating external analytics services, or debugging tracking issues.
15