5SK5
5SK5

Reputation: 169

How do I catch more than one exception type?

I have the following code -

public function getPosts($limit = 25, $author = null) {

    try {

    } catch(\GuzzleHttp\Exception\ClientException $e) {
        return [];
    }

    return [];
}

I added this b/c when the page 404s I get the ClientException, however if the server returns a 500 error I get a ServerException - I tried just replacing this with catch(Exception $ex), but I still get the unhandled/uncaught exception error.

Upvotes: 1

Views: 2091

Answers (4)

Iceman
Iceman

Reputation: 6145

The catch can be chained one after the other for handling multiple Error Types.

public function getPosts($limit = 25, $author = null) {

    try {

    } catch(\GuzzleHttp\Exception\ClientException $e) {
        return [];
    } catch(\GuzzleHttp\Exception\ServerException $e) {
        return [];
    }

    return [];
}

Upvotes: 0

Ray
Ray

Reputation: 41508

You can have multiple catch blocks for different exception types in php:

  try {

    } catch(\GuzzleHttp\Exception\ClientException $e) {
        return [];
    } catch(\GuzzleHttp\Exception\ServerException  $e) {
       //handle it...
 }

However, the assuming the Guzzle exceptions extend the general php Exception class (which of course they do), changing it to just Exception $e should work. Are you sure this is where the exception is being thrown?

On the guzzle site http://docs.guzzlephp.org/en/latest/quickstart.html#exceptions you can see GuzzleHttp\Exception\TransferException base for all the client/server extensions, so you could just try to catch a GuzzleHttp\Exception\TransferException;

Upvotes: 3

jhonatan teixeira
jhonatan teixeira

Reputation: 800

Just keep catching

public function getPosts($limit = 25, $author = null) {

    try {

    } catch(\GuzzleHttp\Exception\ClientException $e) {
        return [];
    } catch (ServerException) {
        //some code
    }

    return [];
}

be aware of namespaces, if you try to catch Exception it will catch all exceptions, if it did not, maybe you didnt include the exception as use Exception or tried to catch \Exception

Upvotes: 0

Marc B
Marc B

Reputation: 360922

just list multiple catches:

try {
   ...
} catch (FooException e) {
   ...
} catch (BarException e) {
   ...
} catch (Exception e) {
   ...
}

Upvotes: 2

Related Questions