Skip to content

Error Handling

Properly handling errors is essential for building robust messaging applications with the MsGine SDK.

Error Types

The SDK throws different types of errors depending on the situation:

MsGineError

The base error class for all SDK-specific errors:

typescript
import { MsGineError } from '@msgine/sdk'

try {
  await client.sendSms({
    to: '+256701521269',
    message: 'Hello!'
  })
} catch (error) {
  if (error instanceof MsGineError) {
    console.error('MsGine API Error:', error.message)
    console.error('Status Code:', error.statusCode)
    console.error('Error Code:', error.code)
  }
}

Error Properties

All MsGineError instances include:

PropertyTypeDescription
messagestringHuman-readable error description
statusCodenumberHTTP status code (e.g., 400, 401, 500)
codestringMachine-readable error code
detailsobjectAdditional error context

Common Error Codes

Authentication Errors

typescript
{
  code: 'unauthorized',
  statusCode: 401,
  message: 'Invalid or missing API token'
}

Solutions:

  • Verify your API token is correct
  • Check that the token hasn't expired
  • Ensure the token is properly loaded from environment variables

Validation Errors

typescript
{
  code: 'invalid_phone_number',
  statusCode: 400,
  message: 'The phone number must be in E.164 format',
  details: {
    field: 'to',
    value: '0701234567'
  }
}

Solutions:

  • Use E.164 format: +[country code][number]
  • Example: +256701521269 (not 0701521269)

Rate Limit Errors

typescript
{
  code: 'rate_limit_exceeded',
  statusCode: 429,
  message: 'Too many requests. Please try again later.',
  details: {
    retryAfter: 60
  }
}

Solutions:

  • The SDK automatically retries with exponential backoff
  • Consider implementing request queuing for high-volume applications

Retry Logic

The SDK includes automatic retry logic for transient errors:

typescript
const client = new MsGineClient({
  apiToken: process.env.MSGINE_API_TOKEN!,
  retryConfig: {
    maxRetries: 3,
    initialDelayMs: 1000,
    maxDelayMs: 10000,
    backoffMultiplier: 2
  }
})

Default Retry Behavior

  • Retryable errors: Network errors, 5xx server errors, rate limits
  • Non-retryable errors: 4xx client errors (except 429)
  • Backoff strategy: Exponential backoff with jitter

Error Handling Best Practices

1. Always Use Try-Catch

typescript
async function sendMessage() {
  try {
    const result = await client.sendSms({
      to: '+256701521269',
      message: 'Hello!'
    })
    return result
  } catch (error) {
    if (error instanceof MsGineError) {
      // Handle SDK errors
      console.error('API Error:', error.code, error.message)
    } else {
      // Handle unexpected errors
      console.error('Unexpected error:', error)
    }
    throw error
  }
}

2. Check Error Codes

typescript
try {
  await client.sendSms({ to: phone, message: text })
} catch (error) {
  if (error instanceof MsGineError) {
    switch (error.code) {
      case 'invalid_phone_number':
        console.error('Invalid phone:', error.details)
        break
      case 'rate_limit_exceeded':
        console.error('Rate limited, retry after:', error.details.retryAfter)
        break
      case 'unauthorized':
        console.error('Authentication failed')
        break
      default:
        console.error('API error:', error.message)
    }
  }
}

3. Log Errors for Debugging

typescript
import { MsGineClient, MsGineError } from '@msgine/sdk'

const client = new MsGineClient({
  apiToken: process.env.MSGINE_API_TOKEN!,
  onError: (error) => {
    // Custom error logging
    console.error('[MsGine SDK Error]', {
      code: error.code,
      message: error.message,
      statusCode: error.statusCode,
      timestamp: new Date().toISOString()
    })
  }
})

4. Graceful Degradation

typescript
async function sendSmsWithFallback(to: string, message: string) {
  try {
    return await client.sendSms({ to, message })
  } catch (error) {
    if (error instanceof MsGineError) {
      // Log to monitoring service
      await logToMonitoring(error)

      // Attempt fallback notification method
      await sendEmailNotification(to, message)

      return null
    }
    throw error
  }
}

Timeout Errors

Configure request timeouts to prevent hanging requests:

typescript
const client = new MsGineClient({
  apiToken: process.env.MSGINE_API_TOKEN!,
  timeoutMs: 30000 // 30 seconds
})

Validation Errors

The SDK validates inputs before making API requests:

typescript
try {
  await client.sendSms({
    to: 'invalid-number', // Will throw validation error
    message: 'Hello!'
  })
} catch (error) {
  // Validation happens client-side before API call
  console.error('Validation error:', error.message)
}

Next Steps

Released under the MIT License.