adlacruzes / php-base-exception
PHP base exception with default message and custom value
Installs: 31 214
Dependents: 1
Suggesters: 0
Security: 0
Stars: 0
Watchers: 0
Forks: 0
Open Issues: 0
Requires
- php: ^7.2 || ^8.0
- ext-mbstring: *
Requires (Dev)
- ergebnis/composer-normalize: ^2.19 || ^2.20 || ^2.28.3
- friendsofphp/php-cs-fixer: ^v3.2.1 || v3.9.6
- phpstan/phpstan: ^1.8.6
- phpstan/phpstan-strict-rules: ^1.4.4
- phpunit/phpunit: ^8.5.30 || ^9.5.25
README
PHP base exception is a library that provides exceptions with a default message and a custom value in an easy way.
Requirements
PHP needs to be a minimum version of PHP 7.2.
Installation
The recommended way to install is through Composer.
composer require adlacruzes/php-base-exception
Usage
Create an exception that extends from BaseException.
use Adlacruzes\Exceptions\BaseException; class SomethingNotFoundException extends BaseException {}
Then the exception can be called with no arguments.
try { throw new SomethingNotFoundException(); } catch (SomethingNotFoundException $e) { echo $e->getMessage(); }
The method getMessage()
returns an auto generated message based on the class name without typing anything more.
echo $e->getMessage(); // Something not found
Default message
You can choose a default message instead. Just initialize the message variable.
class SomethingNotFoundException extends BaseException { /** * @var mixed */ protected $message = 'This is a default message'; }
try { throw new SomethingNotFoundException(); } catch (SomethingNotFoundException $e) { echo $e->getMessage(); }
echo $e->getMessage(); // This is a default message
Message with contextual information
In addition to the message, you can provide more information to the exception and it will append to the result.
try { throw new SomethingNotFoundException('information'); } catch (SomethingNotFoundException $e) { echo $e->getMessage(); }
And the output will be:
echo $e->getMessage(); // Something not found: information