i’m trying to build my own restAPI so i have to response some http errors if there should be. I created a class called Response and i can use the properties in different php files in try catch method and i can response the errors. But while i am doing that, i always create a response object and use the properties that i need from response class. Here is a little example of that :
if(array_key_exists("newsid",$_GET)){
$news_id = $_GET['newsid'];
if($news_id == '' || !is_numeric($news_id)){
$response = new Response();
$response->setHttpStatusCode(400);
$response->setSuccess(false);
$response->addMessage("Haber id'si boş olamaz veya sayı olmalı!");
$response->send();
exit;
}
if($_SERVER['REQUEST_METHOD'] === 'GET'){
//Gets a Single News
try{
$stmt = $readDB->prepare("SELECT id,title,details,poster_link FROM tb_news WHERE id = :id"); //syntax for prepared statements and PDO.
$stmt->bindParam(':id',$news_id,PDO::PARAM_INT);
$stmt->execute();
$rowCount = $stmt->rowCount();
if($rowCount === 0){
//Set up response for unsuccessful return
$response = new Response();
$response->setHttpStatusCode(404);
$response->setSuccess(false);
$response->addMessage("Haber Bulunamadı");
$response->send();
exit;
}
As you see here, every time i control some condition, i create a response object and using the properties one by one and send the response. So how can i do it more effectively in my case? Can you give me some examples on that because i’m new to programming i can think about the logic but i can’t mirror in my codes. I’m looking forward to hear your advices.
>Solution :
Exceptions are used exactly for that.
First, create a custom exception,
class HttpException extends RuntimeException {}
Then change your code to
if($news_id == '' || !is_numeric($news_id)){
throw new HttpException("Haber id'si boş olamaz veya sayı olmalı!", 400);
}
Then write an Exception handler (as you need one anyway) and add a condition in the processing results
$response = new Response();
$response->setSuccess(false);
if ($e instanceof HttpException) {
$response->setHttpStatusCode($e->getCode());
$response->addMessage($e->getMessage());
} else { // a default error handler
error_log($e);
$response->setHttpStatusCode(500);
$response->addMessage("Server error");
}
$response->send();
exit;