Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert API errors codes to exceptions

Tags:

exception

php

api

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:

  • have a separate MyApiThisAndThatError class for each error code?
  • or have a generic class MyApiError and provide API error code as an argument?

I'm also open to alternative suggestions.

like image 383
georg Avatar asked Dec 12 '22 16:12

georg


1 Answers

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.

like image 64
bubba Avatar answered Feb 01 '23 23:02

bubba