PhpThrow (Beta) is a PHP package for throwing custom exceptions with ease.
- Provides custom exception classes with additional functionality.
- Easy to use and integrate into existing projects.
You can install PhpThrow via Composer:
composer require sandromiguel/php-throw
The following code shows how to use the native InvalidArgumentException
class and the ThrowInvalidArgumentException
class to throw an exception if the provided value is less than zero:
try {
$value = -5;
if ($value < 0) {
throw new InvalidArgumentException('The value must be greater than or equal to 0.');
}
// ...
} catch (InvalidArgumentException $e) {
echo $e->getMessage();
}
try {
$value = -5;
ThrowInvalidArgumentException::ifZeroOrNegative($value);
// ...
} catch (ThrowInvalidArgumentException $e) {
echo $e->getMessage();
}
ThrowInvalidArgumentException
extends the built-in InvalidArgumentException
and provides helper methods for throwing exceptions related to invalid arguments.
create($message)
: Creates a new instance of the exception with the given message.
$email = 'not-a-valid-email-address';
try {
// Validate the email address
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw ThrowInvalidArgumentException::create('Invalid email address');
}
// ...
} catch (ThrowInvalidArgumentException $e) {
echo $e->getMessage(); // Output: Invalid email address
}
ifZeroOrNegative($value, $message = null)
: Throws an exception if the numeric value is less than 0.
try {
ThrowInvalidArgumentException::ifZeroOrNegative(-1);
} catch (\PhpThrow\ThrowInvalidArgumentException $e) {
echo $e->getMessage(); // Output: The value must be greater than or equal to 0.
}
ifZeroOrNegativeWithValue($value, $message = null)
: Throws an exception if the numeric value is negative, including the value in the error message.
try {
ThrowInvalidArgumentException::ifZeroOrNegativeWithValue(-1);
} catch (\PhpThrow\ThrowInvalidArgumentException $e) {
echo $e->getMessage(); // Output: The value -1 must be greater than or equal to 0.
}
You can also use a custom message without the placeholder:
ThrowInvalidArgumentException::ifZeroOrNegativeWithValue(
-1,
'Value must be positive'
); // Output: Value must be positive. Provided -1
Want to contribute? All contributions are welcome. Read the contributing guide.
If you have questions tweet me at @sandro_m_m or open an issue.
See CHANGELOG.md
This project is licensed under the MIT License - see the LICENSE file for details
- Implement additional exception classes and methods for common validations
**~ sharing is caring ~**