Integration Guide

Localized API errors in frontend applications

KhaleejiAPI errors include a stable machine-readable code and English and Arabic message fields. Select the message using your app's chosen locale, then render it as text in the framework you use.

Error response shape

Non-2xx responses use an error object. The stable code is for application logic; messageEn and messageAr are for display. Prefer the selected language field, then fall back to the other message fields for older or partially localized responses. The legacy message field is not a locale selector.

json
{
"error": {
"code": "INVALID_PARAMETER",
"message": "Query parameter \"to\" is required",
"messageEn": "Query parameter \"to\" is required",
"messageAr": "معلمة الاستعلام \"to\" مطلوبة."
}
}

Never branch on translated text. Use error.code for program behavior, and provide your own generic localized message when the body is invalid, missing, or has no usable message. If a message could reveal sensitive input or implementation details, map its code to app-owned copy instead of echoing it to the user.

React

This client example calls your own same-origin proxy, safely narrows the parsed JSON from unknown, and renders the selected message with React's escaped text interpolation.

tsx
import { useState } from "react"
type JsonObject = Record<string, unknown>
function asObject(value: unknown): JsonObject | undefined {
return typeof value === "object" && value !== null && !Array.isArray(value)
? value as JsonObject
: undefined
}
function apiErrorMessage(body: unknown, locale: string): string {
const error = asObject(asObject(body)?.error)
const fallback = locale.startsWith("ar")
? "تعذر إكمال الطلب. يرجى المحاولة مرة أخرى."
: "We couldn't complete the request. Please try again."
if (!error) return fallback
const candidates = locale.startsWith("ar")
? [error.messageAr, error.messageEn, error.message]
: [error.messageEn, error.message, error.messageAr]
return candidates.find(
(value): value is string => typeof value === "string" && value.trim().length > 0,
) ?? fallback
}
export function ValidateButton({ locale }: { locale: string }) {
const [error, setError] = useState("")
async function validate() {
try {
const response = await fetch("/api/khaleeji/v1/iban/validate?iban=...")
const body: unknown = await response.json().catch(() => null)
setError(response.ok ? "" : apiErrorMessage(body, locale))
} catch {
setError(locale.startsWith("ar")
? "تعذر الاتصال بالخدمة. يرجى المحاولة مرة أخرى."
: "The service could not be reached. Please try again.")
}
}
return (
<div dir={locale.startsWith("ar") ? "rtl" : "ltr"}>
<button onClick={validate}>Validate</button>
{error && <p role="alert">{error}</p>}
</div>
)
}

Vue

Vue's normal text interpolation escapes the message. Keepv-html out of error display code.

vue
<script setup lang="ts">
import { ref } from "vue"
const locale = ref("ar")
const errorMessage = ref("")
function apiErrorMessage(body: unknown): string {
const root = typeof body === "object" && body !== null && !Array.isArray(body)
? body as Record<string, unknown>
: undefined
const error = root?.error
if (typeof error !== "object" || error === null || Array.isArray(error)) {
return locale.value.startsWith("ar")
? "تعذر إكمال الطلب. يرجى المحاولة مرة أخرى."
: "We couldn't complete the request. Please try again."
}
const fields = error as Record<string, unknown>
const candidates = locale.value.startsWith("ar")
? [fields.messageAr, fields.messageEn, fields.message]
: [fields.messageEn, fields.message, fields.messageAr]
return candidates.find(
(value): value is string => typeof value === "string" && value.trim().length > 0,
) ?? (locale.value.startsWith("ar")
? "تعذر إكمال الطلب. يرجى المحاولة مرة أخرى."
: "We couldn't complete the request. Please try again.")
}
async function validate() {
try {
const response = await fetch("/api/khaleeji/v1/iban/validate?iban=...")
const body: unknown = await response.json().catch(() => null)
errorMessage.value = response.ok ? "" : apiErrorMessage(body)
} catch {
errorMessage.value = locale.value.startsWith("ar")
? "تعذر الاتصال بالخدمة. يرجى المحاولة مرة أخرى."
: "The service could not be reached. Please try again."
}
}
</script>
<template>
<div :dir="locale.startsWith('ar') ? 'rtl' : 'ltr'">
<button @click="validate">Validate</button>
<p v-if="errorMessage" role="alert">{{ errorMessage }}</p>
</div>
</template>

Flutter

The example uses the http package to call your backend and Text for escaped UI output. Use your app's selected locale rather than inferring it from the error.

dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
String apiErrorMessage(String responseBody, String locale) {
final fallback = locale.startsWith('ar')
? 'تعذر إكمال الطلب. يرجى المحاولة مرة أخرى.'
: "We couldn't complete the request. Please try again.";
Object? decoded;
try {
decoded = jsonDecode(responseBody);
} on FormatException {
return fallback;
}
if (decoded is! Map || decoded['error'] is! Map) return fallback;
final error = decoded['error'] as Map;
final candidates = locale.startsWith('ar')
? [error['messageAr'], error['messageEn'], error['message']]
: [error['messageEn'], error['message'], error['messageAr']];
for (final value in candidates) {
if (value is String && value.trim().isNotEmpty) return value;
}
return fallback;
}
Future<String?> validate(String iban, String locale) async {
final uri = Uri.https(
'app.example.com',
'/api/khaleeji/v1/iban/validate',
{'iban': iban},
);
try {
final response = await http.get(uri);
if (response.statusCode >= 200 && response.statusCode < 300) return null;
return apiErrorMessage(response.body, locale);
} catch (_) {
return locale.startsWith('ar')
? 'تعذر الاتصال بالخدمة. يرجى المحاولة مرة أخرى.'
: 'The service could not be reached. Please try again.';
}
}
Text errorText(String message, String locale) => Text(
message,
textDirection: locale.startsWith('ar') ? TextDirection.rtl : TextDirection.ltr,
);

Swift / SwiftUI

Decode the body defensively with JSONSerialization and display the result as a Text value. Apply right-to-left layout when the selected app locale is Arabic.

swift
import Foundation
import SwiftUI
func apiErrorMessage(from data: Data, locale: String) -> String {
let fallback = locale.hasPrefix("ar")
? "تعذر إكمال الطلب. يرجى المحاولة مرة أخرى."
: "We couldn't complete the request. Please try again."
guard
let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let error = root["error"] as? [String: Any]
else { return fallback }
let candidates: [Any?] = locale.hasPrefix("ar")
? [error["messageAr"], error["messageEn"], error["message"]]
: [error["messageEn"], error["message"], error["messageAr"]]
return candidates
.compactMap { $0 as? String }
.first { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
?? fallback
}
func loadErrorMessage(locale: String) async -> String? {
guard let url = URL(string: "https://app.example.com/api/khaleeji/v1/iban/validate?iban=...")
else { return nil }
do {
let (data, response) = try await URLSession.shared.data(from: url)
guard let status = (response as? HTTPURLResponse)?.statusCode,
!(200..<300).contains(status) else { return nil }
return apiErrorMessage(from: data, locale: locale)
} catch {
return locale.hasPrefix("ar")
? "تعذر الاتصال بالخدمة. يرجى المحاولة مرة أخرى."
: "The service could not be reached. Please try again."
}
}
struct ErrorMessage: View {
let message: String
let locale: String
var body: some View {
Text(message)
.environment(\.layoutDirection, locale.hasPrefix("ar") ? .rightToLeft : .leftToRight)
}
}