Error Handling - Nexa Documentation

Error Handling

Penanganan Error

API menggunakan sistem penanganan error yang terstandarisasi untuk memastikan response error yang konsisten dan informatif.

Format Error Response

{
    "status": "error",
    "code": 400|401|403|404|500,
    "message": "Pesan error yang deskriptif",
    "errors": {
        "field": "Detail error untuk field"
    },
    "timestamp": 1234567890
}

Kode Status HTTP

Kode Kategori Deskripsi
200 Success Request berhasil
201 Created Resource berhasil dibuat
400 Bad Request Request tidak valid
401 Unauthorized Autentikasi diperlukan
403 Forbidden Tidak memiliki akses
404 Not Found Resource tidak ditemukan
500 Server Error Error internal server

Contoh Error Response

Validation Error (400)

{
    "status": "error",
    "code": 400,
    "message": "Validasi gagal",
    "errors": {
        "username": "Username harus diisi",
        "email": "Format email tidak valid"
    },
    "timestamp": 1710766800
}

Authentication Error (401)

{
    "status": "error",
    "code": 401,
    "message": "Unauthorized access",
    "errors": {
        "auth": "Token tidak valid atau expired"
    },
    "timestamp": 1710766800
}

Not Found Error (404)

{
    "status": "error",
    "code": 404,
    "message": "Resource tidak ditemukan",
    "errors": {
        "id": "Data dengan ID 123 tidak ditemukan"
    },
    "timestamp": 1710766800
}

Implementasi Error Handler

class ApiController {
    protected function handleError($error, $code = 500) {
        return [
            'status' => 'error',
            'code' => $code,
            'message' => $error->getMessage(),
            'errors' => $this->formatErrors($error),
            'timestamp' => time()
        ];
    }

    protected function formatErrors($error) {
        if ($error instanceof ValidationException) {
            return $error->getErrors();
        }

        return [
            'general' => $error->getMessage()
        ];
    }

    protected function validationError($errors) {
        return $this->response([
            'status' => 'error',
            'code' => 400,
            'message' => 'Validasi gagal',
            'errors' => $errors
        ], 400);
    }
}

Best Practices

  • Gunakan kode HTTP status yang sesuai
  • Berikan pesan error yang jelas dan informatif
  • Sertakan detail error untuk setiap field yang bermasalah
  • Jangan tampilkan error teknis ke client
  • Log semua error server untuk debugging
  • Implementasikan rate limiting untuk mencegah abuse

Client-Side Error Handling

// Example using fetch
fetch('/api/resource')
    .then(response => {
        if (!response.ok) {
            return response.json().then(err => {
                throw new Error(err.message);
            });
        }
        return response.json();
    })
    .then(data => {
        // Handle success
    })
    .catch(error => {
        // Handle error
        console.error('Error:', error.message);
    });