Verbs errors
Error handling in Verbs can be tricky, because it's hard to know where exactly to put your validation logic. Do you want to put it in the event (and then lose some API niceties that Laravel provides), or put it somewhere before your event gets fired, and trust that data has been validated? (Or, do you do both and have a little duplication of code?)
Verbs has an minimally-documented onError
helper that can help address this
issue. Let's take a look.
Imagine you had the following event:
1class MoneyDeposited extends Event 2{ 3 public function __construct( 4 public int $cents, 5 ) {} 6 7 public function validate() 8 { 9 $this->assert($this->cents > 0, CentsMustBePositive::class);10 $this->assert($this->cents <= 10_000_00, DepositOverLimit::class);11 }12 13 // ...14}
Verbs lets you easily translate that exception in your controller to a validation error:
1class BankAccountController 2{ 3 public function deposit(Request $request) 4 { 5 MoneyDeposited::make() 6 // If you return an array from `onError`, it will be translated 7 // to a validation exception automatically by Verbs 8 ->onError(fn(Throwable $e) => match($e::class) { 9 CentsMustBePositive::class => ['cents' => 'You must deposit at least one cent'],10 DepositOverLimit::class => ['cents' => 'You can only deposit up to $10,000 at a time'],11 })12 ->commit(cents: $request->integer('cents'));13 }14}
Now, when you hit the BankAccountController::deposit
endpoint, you'll get nice
validation messages. But if you fire MoneyDeposited
from anywhere else in your
app, invalid inputs will result in an exception!