Skip to main content

Error Handling

This guide explains how to handle errors when using the Marketiger API, including HTTP status codes, custom error types, and best practices for error handling in your application.

HTTP Status Codes

The API uses standard HTTP status codes to indicate the success or failure of a request:

Status CodeNameDescription
200OKEverything worked as expected.
400Bad RequestThe request was unacceptable, often due to missing a required parameter.
401UnauthorizedNo valid API key provided.
402Request FailedThe parameters were valid but the request failed.
403ForbiddenThe API key doesn't have permissions to perform the request.
404Not FoundThe requested resource doesn't exist.
409ConflictThe request conflicts with another request (perhaps due to using the same idempotent key).
424External Dependency FailedThe request couldn't be completed due to a failure in a dependency external to Marketiger.
429Too Many RequestsToo many requests hit the API too quickly. We recommend an exponential backoff of your requests.
500, 502, 503, 504Server ErrorsSomething went wrong on Marketiger's end.

API Error Types

The Marketiger API uses custom error types to provide specific information about what went wrong. These error types are returned in the error.type field of error responses.

Error Type Descriptions

Error TypeValueHTTP StatusDescription
NOT_FOUND0404The requested resource was not found (e.g., project, model, order doesn't exist).
OPERATION_FAILED1400/500The operation could not be completed due to a system or business logic error.
AUTHENTICATION2401Authentication failed (e.g., invalid credentials, expired token, missing token).
INCORRECT_PARAMETERS3400The request parameters are incorrect, missing, or invalid.
NO_PERMISSION4403The user doesn't have permission to perform this action or access this resource.
INCORRECT_PROJECT5400The project reference is incorrect or the user doesn't have access to this project.

Error Response Format

All error responses follow this consistent format:

{
"success": false,
"error": {
"type": "ERROR_TYPE",
"message": "Human-readable error message describing what went wrong"
}
}

Example Error Responses

Authentication Error (401)

{
"success": false,
"error": {
"type": "AUTHENTICATION",
"message": "User email not found"
}
}

Not Found Error (404)

{
"success": false,
"error": {
"type": "NOT_FOUND",
"message": "Project not found are you using the right id?"
}
}

Incorrect Parameters Error (400)

{
"success": false,
"error": {
"type": "INCORRECT_PARAMETERS",
"message": "Order reference should be specified"
}
}

No Permission Error (403)

{
"success": false,
"error": {
"type": "NO_PERMISSION",
"message": "User has no permission for this project"
}
}

Handling Errors

Always check both the HTTP status code and the success field in the response. The API returns errors in a consistent format that makes error handling straightforward.

Error Handling Pattern

  1. Check HTTP Status Code - Indicates the general category of error
  2. Check Response Body - Contains specific error details
  3. Check Error Type - Provides context-specific error information
  4. Handle Appropriately - Take action based on error type

Example: Error Handling in JavaScript

async function handleAPIRequest(url, options) {
try {
const response = await fetch(url, options);
const data = await response.json();

// Check if request was successful
if (!response.ok || !data.success) {
const errorType = data.error?.type;
const errorMessage = data.error?.message;

// Handle based on error type
switch (errorType) {
case 'AUTHENTICATION':
// Token expired or invalid - refresh token
if (response.status === 401) {
await refreshAccessToken();
// Retry request
return handleAPIRequest(url, options);
}
throw new Error(`Authentication failed: ${errorMessage}`);

case 'NOT_FOUND':
throw new Error(`Resource not found: ${errorMessage}`);

case 'INCORRECT_PARAMETERS':
throw new Error(`Invalid parameters: ${errorMessage}`);

case 'NO_PERMISSION':
throw new Error(`Permission denied: ${errorMessage}`);

case 'OPERATION_FAILED':
throw new Error(`Operation failed: ${errorMessage}`);

default:
throw new Error(`API Error: ${errorMessage}`);
}
}

return data.data;
} catch (error) {
// Handle network errors, timeouts, etc.
console.error('Request failed:', error);
throw error;
}
}

Example: Error Handling in C#

public async Task<T> HandleAPIRequest<T>(HttpRequestMessage request)
{
try
{
var response = await _client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();
var apiResponse = JsonSerializer.Deserialize<APIResponse<T>>(content);

if (!response.IsSuccessStatusCode || !apiResponse.Success)
{
var errorType = apiResponse.Error?.Type;
var errorMessage = apiResponse.Error?.Message;

switch (errorType)
{
case "AUTHENTICATION":
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
await RefreshAccessToken();
// Retry request
return await HandleAPIRequest<T>(request);
}
throw new Exception($"Authentication failed: {errorMessage}");

case "NOT_FOUND":
throw new NotFoundException($"Resource not found: {errorMessage}");

case "INCORRECT_PARAMETERS":
throw new ArgumentException($"Invalid parameters: {errorMessage}");

case "NO_PERMISSION":
throw new UnauthorizedAccessException($"Permission denied: {errorMessage}");

case "OPERATION_FAILED":
throw new InvalidOperationException($"Operation failed: {errorMessage}");

default:
throw new Exception($"API Error: {errorMessage}");
}
}

return apiResponse.Data;
}
catch (HttpRequestException ex)
{
// Handle network errors
throw new Exception($"Request failed: {ex.Message}", ex);
}
}

Common Error Scenarios

Authentication Errors

When you receive an AUTHENTICATION error:

  1. 401 Unauthorized - Token expired or invalid

    • Solution: Refresh your access token or re-authenticate
  2. User not found - Email doesn't exist in system

    • Solution: Verify the email address or create an account

Not Found Errors

When you receive a NOT_FOUND error:

  1. Project not found - Project ID doesn't exist

    • Solution: Verify the project ID using GetProjects
  2. Model not found - Model ID doesn't exist

    • Solution: Verify the model ID or check project access
  3. Order not found - Order ID doesn't exist

    • Solution: Verify the order ID or check permissions

Permission Errors

When you receive a NO_PERMISSION error:

  1. Project access denied - User doesn't have access to the project

    • Solution: Contact Marketiger to have a project assigned to your account
  2. Operation not allowed - User doesn't have permission for this operation

    • Solution: Contact support for assistance

Parameter Errors

When you receive an INCORRECT_PARAMETERS error:

  1. Missing required field - Required parameter not provided

    • Solution: Check endpoint documentation for required fields
  2. Invalid format - Parameter format is incorrect (e.g., invalid GUID, country code)

    • Solution: Validate parameter format before sending
  3. Invalid value - Parameter value is out of range or invalid

    • Solution: Check allowed values in endpoint documentation

Rate Limiting

If you receive a 429 Too Many Requests status code, the API is rate limiting your requests. The response headers will include information about when you can retry:

  • X-RateLimit-Limit: Maximum number of requests allowed
  • X-RateLimit-Remaining: Number of requests remaining in the current window
  • X-RateLimit-Reset: Unix timestamp when the rate limit resets
  • Retry-After: Number of seconds to wait before retrying

Implement exponential backoff when handling rate limit errors:

async function makeRequestWithRetry(url, options, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
const response = await fetch(url, options);

if (response.status === 429) {
const retryAfter = parseInt(response.headers.get('Retry-After') || '1');
const delay = retryAfter * Math.pow(2, i); // Exponential backoff
await new Promise(resolve => setTimeout(resolve, delay * 1000));
continue;
}

return response;
}

throw new Error('Max retries exceeded');
}

Error Recovery Strategies

Retry Logic

For transient errors (5xx server errors, 429 rate limits), implement retry logic with exponential backoff:

async function retryRequest(url, options, maxRetries = 3) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const response = await fetch(url, options);

// Retry on server errors
if (response.status >= 500 && response.status < 600) {
if (attempt < maxRetries - 1) {
const delay = Math.pow(2, attempt) * 1000; // Exponential backoff
await new Promise(resolve => setTimeout(resolve, delay));
continue;
}
}

return response;
} catch (error) {
if (attempt === maxRetries - 1) throw error;
const delay = Math.pow(2, attempt) * 1000;
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}

Token Refresh

Automatically refresh tokens when authentication errors occur:

async function makeAuthenticatedRequest(url, options) {
let response = await fetch(url, {
...options,
headers: {
...options.headers,
'Authorization': `Bearer ${accessToken}`
}
});

// Auto-refresh on 401
if (response.status === 401) {
const newToken = await refreshAccessToken();
// Retry with new token
response = await fetch(url, {
...options,
headers: {
...options.headers,
'Authorization': `Bearer ${newToken}`
}
});
}

return response;
}

Best Practices

1. Always Check Success Field

Don't rely solely on HTTP status codes. Always check the success field in the response:

const data = await response.json();
if (!data.success) {
// Handle error
}

2. Handle Specific Error Types

Use the custom error types to provide context-specific handling:

switch (data.error?.type) {
case 'AUTHENTICATION':
// Refresh token or re-authenticate
break;
case 'NOT_FOUND':
// Show user-friendly "not found" message
break;
case 'INCORRECT_PARAMETERS':
// Show validation errors to user
break;
}

3. Implement Retry Logic

For transient errors, implement retry with exponential backoff:

  • 5xx errors: Retry with exponential backoff
  • 429 rate limits: Respect Retry-After header
  • Network errors: Retry with exponential backoff

4. Log Errors Appropriately

Log error details for debugging while keeping sensitive information secure:

// Good: Log error type and message
console.error('API Error:', {
type: data.error?.type,
message: data.error?.message,
endpoint: url
});

// Bad: Don't log tokens or sensitive data
// console.error('Request:', { token: accessToken, password: password });

5. Validate Input Before Sending

Prevent errors by validating parameters before making API calls:

function validateOrderRequest(orderDetails) {
if (!orderDetails.projectId || !isValidGuid(orderDetails.projectId)) {
throw new Error('Invalid project ID');
}
if (!orderDetails.orderReference) {
throw new Error('Order reference is required');
}
// ... more validation
}

6. Provide User-Friendly Error Messages

Translate technical error messages into user-friendly messages:

function getUserFriendlyError(errorType, message) {
const errorMessages = {
'AUTHENTICATION': 'Please log in again',
'NOT_FOUND': 'The requested item was not found',
'NO_PERMISSION': 'You don\'t have permission to perform this action',
'INCORRECT_PARAMETERS': 'Please check your input and try again'
};

return errorMessages[errorType] || message;
}

Error Response Examples by Endpoint

Order Creation Errors

// Missing project ID
{
"success": false,
"error": {
"type": "INCORRECT_PARAMETERS",
"message": "Project id is not valid"
}
}

// Missing order reference
{
"success": false,
"error": {
"type": "INCORRECT_PARAMETERS",
"message": "Order reference should be specified"
}
}

// No project access
{
"success": false,
"error": {
"type": "AUTHENTICATION",
"message": "User has no permission for this project"
}
}

Model Retrieval Errors

// Model not found
{
"success": false,
"error": {
"type": "NOT_FOUND",
"message": "Model not found"
}
}

Project Access Errors

// Project not found
{
"success": false,
"error": {
"type": "NOT_FOUND",
"message": "Project not found are you using the right id?"
}
}

Next Steps