amirhossein5 / return-error
v2.0.0
2025-02-10 11:21 UTC
Requires
- php: ^8.2
Requires (Dev)
- phpstan/phpstan: ^2.0
- phpunit/phpunit: ^11.4
README
- requires php8.2
composer require amirhossein5/return-error
Usage
Given you have a function that might return an error or value:
enum DivisionErrors { case DIVISION_BY_ZERO; } function divide(int $num, int $divideBy): int|ReturnError { if ($divideBy === 0) { return new ReturnError( message: "can't divide by zero", type: DivisionErrors::DIVISION_BY_ZERO, ); } return $num / $divideBy; } $divisionResult = divide(20, 0); if ($divisionResult instanceof ReturnError) { if ($divisionResult->type === DivisionErrors::DIVISION_BY_ZERO) { // ... } // ... }
Constructing ReturnError
new ReturnError();
With message:
new ReturnError(message: "something went wrong");
Or with a type which can be a string or enum:
new ReturnError(..., type: 'its_type'); new ReturnError(..., type: Enum::ENUM);
Reporting ReturnError
To log the error message in with stacktrace in laravel logs call report()
method:
(new ReturnError())->report(); // local.ERROR: {"exception":"[object] (Exception(code: 0): at ... (new ReturnError("with message"))->report(); // local.ERROR: message: with message {"exception... (new ReturnError("with message", "its_type"))->report(); // local.ERROR: message: with message, type: its_type {"exception... enum DivisionErrors: string { case DIVISION_BY_ZERO = 'division_by_zero'; } (new ReturnError(type: DivisionErrors::DIVISION_BY_ZERO))->report(); // local.ERROR: type: DIVISION_BY_ZERO {"exception... (new ReturnError(type: BackedDivideErrors::DIVISION_BY_ZERO))->report(); // local.ERROR: type: division_by_zero {"exception... (new ReturnError())->report(additional: 'string'); // local.ERROR: additional: "string" {"exception... (new ReturnError())->report(additional: ['given' => '...']); // local.ERROR: additional: {"given":"..."} {"exception...
Wrapping exceptions
To wrap an exception into a ReturnError class instance use:
$result = ReturnError::wrap(function() { throw new Exception(); }); $result instanceof ReturnError; // true $result = ReturnError::wrap(function(): int { return 2; }); $result === 2; // true
Unwrapping ReturnError
In some cases you might want to throw the ReturnError if a function returns it:
$num = ReturnError::unwrap(divide(20, 0)); // throws exception $num = ReturnError::unwrap(divide(20, 1)); // num is 20