Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How implement error in Rest API?

Tags:

php

mysql

mysqli

I want to know which is the way to implement error in RestAPI, actually if a method in my classes generate an exception I return this ...

if(mysqli_connect_errno()) {
     throw new Exception("Can't connect to db.");
}

... but this is a bad practice 'cause an API should be return a json.

So my idea is create a class called Errors and, in each class, when an error is fired I simply call the relative error number for display the json error.

Someone have another idea?

like image 378
Sevengames Xoom Avatar asked Feb 07 '26 16:02

Sevengames Xoom


1 Answers

I think @Gwendal answer is good but it's no enough just to return a json response, you also have to return the proper http code:

<?php

try {
    // Do your stuff        
} catch (Exception $e) {
    header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
    echo json_encode(array("success" => false, "message" => $e->getMessage()));
    return;
}
like image 189
beni0888 Avatar answered Feb 09 '26 07:02

beni0888