Search code examples
phplaravellistener

Handle exceptions in Laravel Event Listener


I want to handle Exceptions in my Listener exactly in handle() method

/**
 * Handle the event.
 *
 * @param DocumentGenerated $event
 * @return void
 */
public function handle(DocumentGenerated $event)
{
    $data = $event->data;
    $this->generateDoc($data);
}

After I read the documentation I found that the handle() method of the listener should return false to stop the event propagation.

I changed the return type of the handle() method from void to boolean and tried returning false but it didn't stop the event propagation.


Solution

  • You can handle exceptions by catching the exceptions and returning false. Example:

      /**
     * Handle the event.
     *
     * @param DocumentGenerated $event
     * @return void
     */
    public function handle(FirstPaymentScheduleCreated $event)
    {
      try {
        $data = $event->data;
        $this->generateDoc($data);
    
       }catch (Exception $e) {
        //Handle the exception
        return false; //stop event propagation
       }
        return true // allow event propagation
    }