Guide

Error Handling

Handle errors gracefully in your ArtaMail integration.

Error Types

The SDK provides typed error classes for different error scenarios:

typescript
import {
ArtaMailError, // Base error class
ValidationError, // Invalid input (400)
AuthenticationError, // Invalid API key (401)
NotFoundError, // Resource not found (404)
RateLimitError // Too many requests (429)
} from '@artamail/sdk';

Basic Error Handling

typescript
try {
await artamail.send({
template: 'welcome',
data: { name: 'John' }
});
} catch (error) {
if (error instanceof ArtaMailError) {
console.error('ArtaMail error:', error.message);
console.error('Error code:', error.code);
console.error('HTTP status:', error.status);
} else {
console.error('Unexpected error:', error);
}
}

Handling Specific Errors

Validation Errors

Invalid input data (missing fields, bad email format, etc.):

typescript
try {
await artamail.send({
to: 'invalid-email',
template: 'welcome'
});
} catch (error) {
if (error instanceof ValidationError) {
console.error('Validation failed:', error.message);
// → "Invalid email address: invalid-email"
if (error.details) {
console.error('Details:', error.details);
// → { field: 'to', reason: 'invalid_format' }
}
}
}

Authentication Errors

Invalid or missing API key:

typescript
try {
await artamail.send({ ... });
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('Auth failed:', error.message);
// → "Invalid or missing API key"
// Check your ARTAMAIL_API_KEY environment variable
}
}

Not Found Errors

Template, contact, or email doesn't exist:

typescript
try {
await artamail.send({
template: 'nonexistent-template'
});
} catch (error) {
if (error instanceof NotFoundError) {
console.error('Not found:', error.message);
// → "Template not found: nonexistent-template"
}
}

Rate Limit Errors

Too many requests - implement backoff:

typescript
try {
await artamail.send({ ... });
} catch (error) {
if (error instanceof RateLimitError) {
console.error('Rate limited:', error.message);
if (error.retryAfter) {
console.log(`Retry after ${error.retryAfter} seconds`);
await sleep(error.retryAfter * 1000);
// Retry the request
}
}
}

Next.js Error Handling

API Routes

app/api/send/route.ts
import { sendEmail, ValidationError, RateLimitError } from '@artamail/nextjs/server';
import { NextResponse } from 'next/server';
export async function POST(request: Request) {
try {
const body = await request.json();
const result = await sendEmail({
to: body.email,
template: body.template,
data: body.data
});
return NextResponse.json({ success: true, id: result.id });
} catch (error) {
if (error instanceof ValidationError) {
return NextResponse.json(
{ error: error.message, details: error.details },
{ status: 400 }
);
}
if (error instanceof RateLimitError) {
return NextResponse.json(
{ error: 'Too many requests' },
{ status: 429 }
);
}
console.error('Email send error:', error);
return NextResponse.json(
{ error: 'Failed to send email' },
{ status: 500 }
);
}
}

Server Actions

app/actions.ts
'use server'
import { sendEmail, ValidationError } from '@artamail/nextjs/server';
export async function sendWelcomeEmail(email: string, name: string) {
try {
const result = await sendEmail({
to: email,
template: 'welcome',
data: { name }
});
return { success: true, emailId: result.id };
} catch (error) {
if (error instanceof ValidationError) {
return { success: false, error: error.message };
}
return { success: false, error: 'Failed to send email' };
}
}

Nuxt Error Handling

server/api/send.post.ts
import { sendEmail } from '#artamail/server';
import { ValidationError, RateLimitError } from '@artamail/sdk';
export default defineEventHandler(async (event) => {
const body = await readBody(event);
try {
const result = await sendEmail({
to: body.email,
template: body.template,
data: body.data
});
return { success: true, id: result.id };
} catch (error) {
if (error instanceof ValidationError) {
throw createError({
statusCode: 400,
message: error.message
});
}
if (error instanceof RateLimitError) {
throw createError({
statusCode: 429,
message: 'Too many requests'
});
}
throw createError({
statusCode: 500,
message: 'Failed to send email'
});
}
});

Retry Logic

The SDK has built-in retry logic for transient failures. You can configure it:

typescript
const artamail = new ArtaMail({
apiKey: process.env.ARTAMAIL_API_KEY,
retries: 3, // Number of retry attempts (default: 3)
timeout: 30000 // Request timeout in ms (default: 30000)
});

Automatic Retries

The SDK automatically retries on:

  • Network errors
  • 5xx server errors
  • Rate limit errors (429)

It does NOT retry on:

  • Validation errors (400)
  • Authentication errors (401)
  • Not found errors (404)

Error Reference

ErrorStatusWhen
ValidationError400Invalid input, missing required fields, bad email format
AuthenticationError401Invalid API key, expired token, missing auth header
NotFoundError404Template, contact, or email not found
RateLimitError429Too many requests, check retryAfter property
ArtaMailError500Server error, network issues

Best Practices

  • Always catch errors - Email sending can fail for various reasons
  • Log errors - Include error details for debugging
  • Show user-friendly messages - Don't expose internal errors to users
  • Use test mode - Catch configuration issues early in development
  • Monitor failures - Track error rates in production
Production tip
Always implement proper error handling before going to production. Unhandled errors can lead to poor user experience and missed notifications.