error-contract
Standardized error response handling between frontend and backend. Covers error structure, status codes, and consistent error handling. USE WHEN: user asks about "error handling", "API errors", "error response format", "status codes", "error messages", "validation errors" DO NOT USE FOR: logging - use logging skills, exception handling - use language-specific skills
What this skill does
# Error Contract - Quick Reference
## When NOT to Use This Skill
- **Logging configuration** - Use logging skills
- **Exception handling patterns** - Use language-specific skills
- **Security error handling** - Use security skills
> **Deep Knowledge**: Use `mcp__documentation__fetch_docs` for framework-specific error handling patterns.
## Standard Error Response Structure
### RFC 7807 (Problem Details)
```json
{
"type": "https://api.example.com/errors/validation",
"title": "Validation Error",
"status": 400,
"detail": "The request body contains invalid data",
"instance": "/users/123",
"errors": [
{
"field": "email",
"message": "Invalid email format",
"code": "INVALID_FORMAT"
}
],
"traceId": "abc123-def456"
}
```
### Simple Error Structure
```json
{
"error": {
"code": "VALIDATION_ERROR",
"message": "The request body contains invalid data",
"details": [
{
"field": "email",
"message": "Invalid email format"
}
]
}
}
```
## OpenAPI Error Definition
```yaml
components:
schemas:
Error:
type: object
required:
- code
- message
properties:
code:
type: string
description: Machine-readable error code
example: "VALIDATION_ERROR"
message:
type: string
description: Human-readable error message
example: "Invalid request data"
details:
type: array
items:
$ref: '#/components/schemas/ErrorDetail'
traceId:
type: string
description: Request trace ID for debugging
example: "abc123-def456"
ErrorDetail:
type: object
properties:
field:
type: string
example: "email"
message:
type: string
example: "Invalid email format"
code:
type: string
example: "INVALID_FORMAT"
responses:
BadRequest:
description: Invalid request data
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
example:
code: "VALIDATION_ERROR"
message: "Invalid request data"
details:
- field: "email"
message: "Invalid email format"
Unauthorized:
description: Authentication required
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
example:
code: "UNAUTHORIZED"
message: "Authentication required"
NotFound:
description: Resource not found
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
example:
code: "NOT_FOUND"
message: "User not found"
```
## Status Code Mapping
| Status | Code Constant | When to Use |
|--------|---------------|-------------|
| 400 | `VALIDATION_ERROR` | Invalid request body/params |
| 401 | `UNAUTHORIZED` | Missing or invalid auth |
| 403 | `FORBIDDEN` | Valid auth, insufficient permissions |
| 404 | `NOT_FOUND` | Resource doesn't exist |
| 409 | `CONFLICT` | Duplicate resource, state conflict |
| 422 | `UNPROCESSABLE_ENTITY` | Semantic validation failure |
| 429 | `TOO_MANY_REQUESTS` | Rate limit exceeded |
| 500 | `INTERNAL_ERROR` | Unexpected server error |
| 503 | `SERVICE_UNAVAILABLE` | Temporary unavailability |
## Frontend Error Handling
### TypeScript Error Types
```typescript
// Base error interface matching backend
interface ApiError {
code: string;
message: string;
details?: ErrorDetail[];
traceId?: string;
}
interface ErrorDetail {
field: string;
message: string;
code?: string;
}
// Error class for typed handling
class ApiRequestError extends Error {
constructor(
public readonly code: string,
message: string,
public readonly status: number,
public readonly details?: ErrorDetail[],
public readonly traceId?: string,
) {
super(message);
this.name = 'ApiRequestError';
}
static fromResponse(status: number, body: ApiError): ApiRequestError {
return new ApiRequestError(
body.code,
body.message,
status,
body.details,
body.traceId,
);
}
isValidationError(): boolean {
return this.code === 'VALIDATION_ERROR';
}
isNotFound(): boolean {
return this.code === 'NOT_FOUND';
}
isUnauthorized(): boolean {
return this.code === 'UNAUTHORIZED';
}
getFieldError(field: string): string | undefined {
return this.details?.find(d => d.field === field)?.message;
}
}
```
### Fetch Wrapper with Error Handling
```typescript
async function fetchApi<T>(
url: string,
options?: RequestInit,
): Promise<T> {
const response = await fetch(url, {
...options,
headers: {
'Content-Type': 'application/json',
...options?.headers,
},
});
if (!response.ok) {
const errorBody: ApiError = await response.json();
throw ApiRequestError.fromResponse(response.status, errorBody);
}
return response.json();
}
// Usage
try {
const user = await fetchApi<User>('/api/users/123');
} catch (error) {
if (error instanceof ApiRequestError) {
if (error.isNotFound()) {
showNotification('User not found');
} else if (error.isValidationError()) {
setFormErrors(error.details);
} else {
showNotification(error.message);
}
}
}
```
### React Error Handling
```typescript
// Error boundary for unexpected errors
class ErrorBoundary extends React.Component<Props, State> {
state = { hasError: false, error: null };
static getDerivedStateFromError(error: Error) {
return { hasError: true, error };
}
render() {
if (this.state.hasError) {
return <ErrorFallback error={this.state.error} />;
}
return this.props.children;
}
}
// Form validation errors
function UserForm() {
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
const mutation = useMutation({
mutationFn: createUser,
onError: (error) => {
if (error instanceof ApiRequestError && error.isValidationError()) {
const errors: Record<string, string> = {};
error.details?.forEach(detail => {
errors[detail.field] = detail.message;
});
setFieldErrors(errors);
} else {
toast.error(error.message);
}
},
});
return (
<form onSubmit={handleSubmit}>
<input name="email" />
{fieldErrors.email && <span className="error">{fieldErrors.email}</span>}
</form>
);
}
```
### React Query Error Handling
```typescript
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: (failureCount, error) => {
// Don't retry on client errors
if (error instanceof ApiRequestError && error.status < 500) {
return false;
}
return failureCount < 3;
},
},
mutations: {
onError: (error) => {
// Global error handler
if (error instanceof ApiRequestError) {
if (error.isUnauthorized()) {
window.location.href = '/login';
}
}
},
},
},
});
```
## Backend Error Implementation
### NestJS
```typescript
// Error filter
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
catch(exception: unknown, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
let status = 500;
let errorResponse: ApiError = {
code: 'INTERNAL_ERROR',
message: 'An unexpected error occurred',
traceId: request.headers['x-trace-id'] as string,
};
if (exception instanceof HttpException) {
status = exception.getStatus();
const exceptionResponse = exception.getResponse();
if (typeof exceptionResponse === 'object') {
errorResponse = {
...errRelated in Web Dev
generating-lwc-components
IncludedLightning Web Components with PICKLES methodology and 165-point scoring. Use this skill when the user creates or edits LWC components, builds wire service patterns, or writes Jest tests for LWC. TRIGGER when: user creates/edits LWC components, touches lwc/**/*.js, .html, .css, .js-meta.xml files, or asks about wire service, SLDS, or Jest LWC tests. DO NOT TRIGGER when: Apex classes (use generating-apex), Aura components, or Visualforce.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Set up queries with useQuery, mutations with useMutation, configure QueryClient caching strategies, implement optimistic updates, and handle infinite scroll with useInfiniteQuery. Use when: setting up data fetching in React projects, migrating from v4 to v5, or fixing object syntax required errors, query callbacks removed issues, cacheTime renamed to gcTime, isPending vs isLoading confusion, keepPreviousData removed problems.
document-processor-api
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
nutrient-document-processing
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Covers useMutationState, simplified optimistic updates, throwOnError, network mode (offline/PWA), and infiniteQueryOptions. Use when setting up data fetching, fixing v4→v5 migration errors (object syntax, gcTime, isPending, keepPreviousData), or debugging SSR/hydration issues with streaming server components.
accelint-nextjs-best-practices
IncludedNext.js performance optimization and best practices. Use when writing Next.js code (App Router or Pages Router); implementing Server Components, Server Actions, or API routes; optimizing RSC serialization, data fetching, or server-side rendering; reviewing Next.js code for performance issues; fixing authentication in Server Actions; or implementing Suspense boundaries, parallel data fetching, or request deduplication.