Kotchasan Framework Documentation
ApiException
ApiException
Kotchasan\ApiException เป็น Exception Class สำหรับจัดการข้อผิดพลาดใน API รองรับการกำหนด HTTP Status Code และข้อความ Error Message
การใช้งาน
ใช้ throw เพื่อสร้าง Exception เมื่อเกิดข้อผิดพลาดในการประมวลผล API โดย ApiController (หรือ Global Error Handler) จะนำ Exception นี้ไปสร้างเป็น JSON Response มาตรฐาน
use Kotchasan\ApiException;
// สร้าง Exception พร้อม Message และ Code
throw new ApiException('User not found', 404);Constructor
public function __construct(string $message = '', int $code = 0, Throwable $previous = null)$message: ข้อความแสดงข้อผิดพลาด$code: HTTP Status Code (เช่น 400, 401, 403, 404, 500)$previous: Exception ก่อนหน้า (Optional)
ตัวอย่างการใช้งานจริง
การตรวจสอบ Input
if (empty($id)) {
throw new ApiException('ID is required', 400);
}การตรวจสอบสิทธิ์
if (!$user->canAccess()) {
throw new ApiException('Access Denied', 403);
}การสร้าง Custom Exception
สามารถสร้าง Class ที่สืบทอดจาก ApiException เพื่อจัดการ Error เฉพาะทาง
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);ผลลัพธ์ Response
เมื่อ ApiException ถูกจับโดย ApiController จะแปลงเป็น JSON รูปแบบ:
{
"error": "Error Type",
"message": "User not found",
"code": 404
}