Kong / unirest-php

Unirest in PHP: Simplified, lightweight HTTP client library.
http://unirest.io/php
MIT License
1.28k stars 328 forks source link

Better handling of Errors #132

Closed gianniskr closed 6 years ago

gianniskr commented 6 years ago

The Request::send() function throws an Exception when encounters an error. That makes the program to stop abruptly and allows for no way to catch the error gracefully. It should instead return an Error class that contains the error information and let the developer handle the error. It does not need to be something fancy. Just a class that returns the error message, the error id and the curl info.

hutchic commented 6 years ago

why not just catch the exception?

gianniskr commented 6 years ago

The problem is that I can't seem to catch the Exception. I have this function:

    protected function apiGetCall($path, $query = NULL) {
        $headers = array('Accept' => 'application/json');
        if ($query == NULL) {
            $query = array();
        }
        $server = $this->server;
        $fullPath = 'http://' . $server . ':' . $this->port . $path;
        try {
            $request = \Unirest\Request::get($fullPath, $headers, $query);
            return $request;
        } catch (Exception $e) {
            return "Error" . $e->getMessage();
        }
    }

As you see, I try to catch the Exception. The problem is that the Exception is thrown nonetheless. Every time my system says that there is an error with $request = \Unirest\Request::get($fullPath, $headers, $query);. Probably the problem is inside the ::get(). There is no handling of the Exception in there. So if it throws an error, it doesn't cascade to my function.

gianniskr commented 6 years ago

I think the best, non-destructive, option right now is to add try-catch statements to ::get, ::head, ::options, ::connect, ::post, ::delete, ::put, ::patch and ::trace in Request.php.

gianniskr commented 6 years ago

I found the problem. The Request::send returns the bundle-extended Exception class and not the default Exception class. I needed to specifically catch the \Unirest\Exception class in order to handle the error.