Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@idoqo idoqo commented Sep 30, 2019

Hi, which Queue class is being used in the AppServiceProvider class?

@paulund

This comment has been minimized.

Copy link
Owner Author

@paulund paulund commented Sep 30, 2019

@idoqo it's the queue facade.

@idoqo

This comment has been minimized.

Copy link

@idoqo idoqo commented Sep 30, 2019

@idoqo it's the queue facade.

Got it. Thanks!

@jayaVishwakarma

This comment has been minimized.

Copy link

@jayaVishwakarma 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