From 99de175fd8075734f210e8e2ecea7733660e30bb Mon Sep 17 00:00:00 2001 From: Felip Manyer i Ballester <git@res-telae.cat> Date: Tue, 9 Feb 2021 12:35:54 +0100 Subject: [PATCH] Exception handling --- src/Gbif.php | 9 ++++++--- src/GbifException.php | 17 +++++++++++++++++ src/Species.php | 9 ++++++--- 3 files changed, 29 insertions(+), 6 deletions(-) create mode 100644 src/GbifException.php diff --git a/src/Gbif.php b/src/Gbif.php index d9fb2a6..003fb83 100644 --- a/src/Gbif.php +++ b/src/Gbif.php @@ -39,6 +39,9 @@ abstract class Gbif { * * @return array * An array of results. + * + * @throws \ResTelae\Gbif\GbifException + * In case the HTTP request ends with an error. */ protected function gbifGet($uri, array $args = []) { $query_string = $this->formatQueryString($args); @@ -46,11 +49,11 @@ abstract class Gbif { $response = $this->gbifClient->get($uri, ['query' => $query_string]); } catch (RequestException $e) { - error_log((string) $e->getRequest()); + $msg = (string) $e->getRequest(); if ($e->hasResponse) { - error_log((string) $e->getResponse()); + $msg .= (string) $e->getResponse(); + throw new GbifException($msg); } - return []; } $data = (string) $response->getBody(); diff --git a/src/GbifException.php b/src/GbifException.php new file mode 100644 index 0000000..641c701 --- /dev/null +++ b/src/GbifException.php @@ -0,0 +1,17 @@ +<?php + +namespace ResTelae\Gbif; + +/** + * GBIF: exception handler. + */ +class GbifException extends \Exception { + + /** + * {@inheritdoc} + */ + public function __construct($message = '', $code = 0, \Throwable $previous = NULL) { + parent::__construct($message, $code, $previous); + } + +} diff --git a/src/Species.php b/src/Species.php index fc59589..85dd53d 100644 --- a/src/Species.php +++ b/src/Species.php @@ -84,6 +84,9 @@ class Species extends Gbif { * @return array * An array of results. * + * @throws \ResTelae\Gbif\GbifException + * When some arguments are wrong. + * * @see http://www.gbif.org/developer/species#nameUsages */ public function nameUsage(array $args = [], $data = 'all', $key = NULL, $uuid = NULL, $short_name = NULL) { @@ -111,11 +114,11 @@ class Species extends Gbif { ]; if (!in_array($data, $data_choices)) { - // TODO: raise exception. + throw new GbifException('Illegal choice for `data`'); } if ($data != 'all' && !$key) { - // TODO: raise exception. + throw new GbifException('You must specify a key if `data` does not equal `all`'); } if ($data == 'all') { @@ -123,7 +126,7 @@ class Species extends Gbif { } elseif ($data == 'root') { if (!$uuid && !$short_name) { - // TODO: raise exception. + throw new GbifException('`uuid` and `short_name` cannot be both NULL if `data` equals "root"'); } $uri = $uuid ? 'species/' . $uuid : 'species/' . $short_name; } -- GitLab