Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to do error handling more effectively in PHP with OOP?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading