Skip to content

Instantly share code, notes, and snippets.

@paulund
Created August 25, 2018 12:08
Show Gist options
  • Save paulund/c00f0a57bad1834936bf6ee4a4e13309 to your computer and use it in GitHub Desktop.
Save paulund/c00f0a57bad1834936bf6ee4a4e13309 to your computer and use it in GitHub Desktop.
Details of how to send a slack message when a job fails
public function boot()
{
Queue::failing(function (JobFailed $event) use ($slackUrl) {
Notification::route('slack', $slackUrl)->notify(new SlackFailedJob($event));
});
}
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\SlackAttachment;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\Events\JobFailed;
class SlackFailedJob extends Notification implements ShouldQueue
{
use Queueable;
/**
* @var JobFailed
*/
public $event;
/**
* Create a new notification instance.
*
* @param JobFailed $event
*/
public function __construct(JobFailed $event)
{
$this->event = $event;
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return ['slack'];
}
/**
* Get the Slack representation of the notification.
*
* @param mixed $notifiable
* @return SlackMessage
*/
public function toSlack($notifiable)
{
return (new SlackMessage)
->content('A job failed at '.config('app.name'))
->attachment(function (SlackAttachment $attachment) use ($notifiable) {
$attachment->fields([
'Exception message' => $notifiable->event->exception->getMessage(),
'Job class' => $notifiable->event->job->resolveName(),
'Job body' => $notifiable->event->job->getRawBody(),
'Exception' => $notifiable->event->exception->getTraceAsString(),
]);
});
}
}
@idoqo
Copy link

idoqo commented Sep 30, 2019

@idoqo it's the queue facade.

Got it. Thanks!

@jayaVishwakarma
Copy link

jayaVishwakarma commented Oct 29, 2020

$notifiable doesn't have those properties so I had to replace it with $this->event.I am using Laravel 5.8 and it worked for me after following changes:

public function toSlack($notifiable) { return (new SlackMessage) ->content('A job failed at '.config('app.name')) ->attachment(function (SlackAttachment $attachment) use ($notifiable) { $attachment->fields([ 'Exception message' => $this->event->exception->getMessage(), 'Job class' => $this->event->job->resolveName(), 'Job body' => $this->event->job->getRawBody(), 'Exception' => $this->event->exception->getTraceAsString(), ]); }); }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment