Search code examples
laravellaravel-6laravel-queuelaravel-6.2

Laravel setting Job as failed


How do I flag/set a Job as Failed?

I'm using closure function to dispatch a job that calls on external API, and I'd like to manually set if the job is success or failure based on the API response.

Here's my code, I'm using a simple example instead of API calls.

public function sendSMS( $numbers ) {

    dispatch(function () use ( $numbers ) {            
        $this->smsProcess($numbers, $this->note->content);
    });

}

public function smsProcess( $numbers, $message ) {

    $int = random_int( 1, 10 ) * random_int( 1, 10 );

    if ( $int < 50  ) {
        throw ValidationException::withMessages('Less than 50')->status(403);
    } else {
        throw ValidationException::withMessages('Greater than 50')->status(403);
    }
}

When The sendSMS function runs, I can see a pending Job for smsProcess

But when I run the queue:work the job is being Processed and did not fail,

So how do I manually trigger the Job as failed?

If I put some error code on smsProcess I can see the job is marked as Failed Due to php error


Solution

  • You should use the Exception class not the ValidationException

    public function smsProcess( $numbers, $message ) {
    
        $int = random_int( 1, 10 ) * random_int( 1, 10 );
    
        if ( $int < 50  ) {
            throw new \Exception('Less than 50');
        } else {
            throw new \Exception('Greater than 50');
        }
    }