DEV Community

Dimitrios Desyllas
Dimitrios Desyllas

Posted on

Do not re-dispatch jobs but still notify sentry for failure.

In my daily work as php developer, sometimes I need to make a job do not being re-despatched, yet fail and notify the sentry for failure.

So let us suppose we have a job that retrieves some data from DB and e-mails it:


namespace App\Jobs

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class MailStuff implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    private $model;    
    private $email;

    public function __construct(Model $model, string $email)
    {
      $this->model = $model;
      $this->email = trim($email);
    }


   public function handle()
   {
      if(empty($email)){
         throw new RuntimeException("Mail Should not be valid");
      }      

      // Collect data here
      // Send email
   }
}
Enter fullscreen mode Exit fullscreen mode

Also we followed the sentry's documentation and set up the sentry.

In our case job will be re-dispatched and will fail again and still be re-dispatched and fail again etc etc. That will keep the queue busy for no aparent reason. Is email is empty we have no reason to re-dispatch the job, but I need to know that job has been stopped in errorous condition.

Therefore I'll refactor the handle like this:

 public function handle()
   {
      if(empty($email)){
         app('sentry')->captureException(new RuntimeException("Mail Should not be valid"));
         Log::error("Mail Should not be valid");
         return;
      }      

      // Collect data here
      // Send email
   }
Enter fullscreen mode Exit fullscreen mode

What I did is I used the sentry from service container and reported manually an exception. Then I'll just return the function and not proceed further.

The approach is not perfect but it works and does not keep queue busy if it should not be kept busy.

Comment bellow for a better solution.

Top comments (0)