Download the PHP package pnoexz/php-api-exception without Composer
On this page you can find all versions of the php package pnoexz/php-api-exception. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package php-api-exception
PHP API Exception
PHP API Exception relies on the following principles:
- Each exception must be unique.
- Consumers MUST NOT rely on the human readable error message to identify it.
- Comply with PSR-3. See: https://www.php-fig.org/psr/psr-3/
Signature
Examples
Simple usage
Will output the following JSON:
Creating a custom exception
If you need to support an HTTP Status Code that's not on the standard or is missing, it's possible to extend from \Pnoexz\ApiException\Http\ClientError\ClientErrorException
(default level WARNING), \Pnoexz\ApiException\Http\ServerError\ServerErrorException
(default level ERROR) or Pnoexz\ApiException
(no default level).
Sending extra data to the client along with the exception
Suppose we are building an ecommerce system in which users can't have more than one pending cart at the same time. If the user tries to create a new cart, instead of simply displaying an error, we can send the entity to the client so they can gracefully handle the error and display information to the user.
Exception
From the service
Output to the client
Maintaining the previously thrown exception
In this case, we will be catching an exception that contains sensitive data (a raw SQL query). We need to separate what the client will see and what we should log. This might require some extra code in our handler, but when throwing the exception, all we need to do is the pass what we caught to the second parameter.
We can then catch this exception from the calling method and do similarly; maintaining the exception trace and sending back a nice output to the client.
Handler
These examples use the Slim3 error handler but should work similarly with other frameworks.