简体   繁体   中英

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.

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 ;

just list multiple catches:

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

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 [];
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM