interface ApiError {
code: string;
status: number;
message: string;
description: string;
details?: Array<{
field: string;
message: string;
}>;
}
class FirstQuadrantError extends Error {
constructor(
public code: string,
public status: number,
message: string,
public details?: any[],
) {
super(message);
}
}
async function apiRequest<T>(endpoint: string, options?: RequestInit): Promise<T> {
const response = await fetch(`https://api.us.firstquadrant.ai/v5${endpoint}`, {
...options,
headers: {
Authorization: "Bearer YOUR_API_KEY",
"FirstQuadrant-Organization-ID": "org_YOUR_ORG_ID",
"Content-Type": "application/json",
...options?.headers,
},
});
if (!response.ok) {
const error: ApiError = await response.json();
throw new FirstQuadrantError(error.code, error.status, error.message, error.details);
}
return response.json();
}
// Usage with error handling
try {
const contact = await apiRequest("/contacts", {
method: "POST",
body: JSON.stringify({ email: "test@example.com" }),
});
} catch (error) {
if (error instanceof FirstQuadrantError) {
if (error.code === "validation_error") {
// Handle validation errors
error.details?.forEach((detail) => {
console.error(`${detail.field}: ${detail.message}`);
});
}
}
}