I'm working on a PHP interface to some API which can return many (up to one hundred) different error codes. My interface is supposed to throw an exception when such a code is encountered. My PHP is a bit rusty, therefore I'm unsure what would be the most suitable option for a present day php programmer:
MyApiThisAndThatError
class for each error code?MyApiError
and provide API error code as an argument?I'm also open to alternative suggestions.
TLDR: Use a generic MyApiException class that includes the API Error code.
Ralph Schindler wrote a nice article on the general topic at http://ralphschindler.com/2010/09/15/exception-best-practices-in-php-5-3
If you read the whole thing, you will see a section Best Practices In Library Code that demonstrates (I've modified his example for this context):
// usage of bracket syntax for brevity
namespace MyCompany\Component {
interface Exception
{}
class MyApiException
extends \RuntimeException
implements Exception
{}
class Component
{
public static function doSomething()
{
$myApiCall->doSomthing();
if ($myApiCall->hasError) {
throw new MyApiException($myApiCall->getMessage(), $myApiCall->getErrorCode);
}
}
}
}
Assuming the above code, if one were to execute MyCompany\Component\Component::doSomething(), the exception that is emitted from the doSomething() method can be caught by any of the following types: PHP’s Exception, SPL’s RuntimeException the component’s MyCompany\Component\MyApiException, or the component’s MyCompany\Component\Exception. This affords the caller any number of opportunities to catch an exception that emanates from a given component within your library, that is instigated by the API Error returned. Furthermore, by analyzing the types that make up the exception, more semantic meaning can be given to the exceptional situation that just occurred.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With