Kotchasan Framework Documentation

Kotchasan Framework Documentation

ApiException

EN 05 Feb 2026 06:23

ApiException

Kotchasan\ApiException is a custom Exception class for handling API errors, supporting custom HTTP status codes and error messages.

Usage

Use throw to trigger an exception when an error occurs during API processing. The ApiController (or global error handler) will catch this exception and generate a standard JSON response.

use Kotchasan\ApiException;

// Create Exception with Message and Status Code
throw new ApiException('User not found', 404);

Constructor

public function __construct(string $message = '', int $code = 0, Throwable $previous = null)
  • $message: Error description.
  • $code: HTTP Status Code (e.g., 400, 401, 403, 404, 500).
  • $previous: Previous Exception (Optional).

Practical Examples

Input Validation

if (empty($id)) {
    throw new ApiException('ID is required', 400);
}

Access Control

if (!$user->canAccess()) {
    throw new ApiException('Access Denied', 403);
}

Creating Custom Exceptions

You can create classes extending ApiException for specific error handling.

namespace App\Exceptions;

use Kotchasan\ApiException;

class UserNotFoundException extends ApiException
{
    public function __construct($userId)
    {
        parent::__construct("User ID {$userId} does not exist", 404);
    }
}

// Usage
throw new UserNotFoundException(123);

JSON Response

When ApiException is caught by ApiController, it is converted to JSON format:

{
    "error": "Error Type",
    "message": "User not found",
    "code": 404
}