• Stars
    star
    76
  • Rank 420,374 (Top 9 %)
  • Language
    PHP
  • License
    MIT License
  • Created about 5 years ago
  • Updated about 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Laravel package to send notifications when some exceptions are thrown.

Notifiable Exception

Latest Version on Packagist Software License Build Status Coverage Status Quality Score Total Downloads

Laravel package to send notifications when exceptions are thrown.

Install

Via Composer

$ composer require cerbero/notifiable-exception

We might need to install other packages depending on the notification channels we want to use (e.g. Slack, Telegram). Please refer to Laravel Notification Channels for more information.

For better performance notifications are queued, please check the documentation to find out what are the requirements for your queue driver.

Usage

In order to be notifiable, exceptions need to implement the Notifiable interface and use the Notifies trait:

use Cerbero\NotifiableException\Notifiable;
use Cerbero\NotifiableException\Notifies;
use Exception;

class UrgentException extends Exception implements Notifiable
{
    use Notifies;
}

Otherwise, if we don't need to extend a particular exception class, we may just extend the NotifiableException for convenience:

use Cerbero\NotifiableException\Exceptions\NotifiableException;

class UrgentException extends NotifiableException

When notifiable exceptions are not handled manually in a try-catch, they are notified automatically. However when we actually need to handle them we can send their notifications by calling the notify() method in the try-catch:

try {
    $this->methodThrowingNotifiableException();
} catch (NotifiableException $e) {
    $e->notify();
    // exception handling logic
}

Sometimes we might want some channel routes to always be notified when an exception is thrown. If so, we can set default routes for every channel we want to notify in config/notifiable_exception.php:

$ php artisan vendor:publish --tag=notifiable_exception_config

As an example, the following configuration defines a Slack and a mail route that will always be notified when any notifiable exception is thrown:

'default_routes' => [
    'mail' => [
        '[email protected]',
    ],
    'slack' => [
        'https://hooks.slack.com/services/xxx/xxx/xxx',
    ],
],

Please note: this README shows routes in the code for convenience, however it is recommended to set routes in environment variables that can then be read from configuration files.

Different routes might need to be notified depending on what instance of notifiable exception is thrown. Ad hoc channels and routes can be defined in notifiable exceptions themselves by overriding the method getCustomRoutes():

class UrgentException extends NotifiableException
{
    protected function getCustomRoutes(): array
    {
        return [
            'nexmo' => [
                '15556666666',
            ],
        ];
    }
}

In the example above, the phone number +1 555-666-6666 will receive an SMS whenever UrgentException is thrown, alongside with the default routes specified in the configuration.

If we want an exception to notify only its custom routes while ignoring the default ones, we can instruct the method overridesRoutes() to do so:

protected function overridesRoutes(): bool
{
    return true;
}

Messages to send can be customized per channel by overriding the method getMessages():

public function getMessages(): array
{
    return [
        'mail' => (new MailMessage)
            ->error()
            ->subject('An error occurred')
            ->line($this->getMessage()),
        'slack' => (new SlackMessage)
            ->error()
            ->content($content)
            ->attachment(function (SlackAttachment $attachment) {
                $attachment
                    ->title($this->getMessage())
                    ->fields([
                        'File' => $this->getFile(),
                        'Line' => $this->getLine(),
                        'Code' => $this->getCode(),
                        'Previous exception' => $this->getPrevious() ? get_class($this->getPrevious()) : 'none',
                    ]);
            }),
        'nexmo' => (new NexmoMessage)->content($this->getMessage()),
    ];
}

By default Laravel supports some notification channels (e.g. mail, slack), however custom channel classes need to be specified when using third-party solutions. We can define them by overriding the method getCustomChannels():

use NotificationChannels\Telegram\TelegramChannel;

...

public function getCustomChannels(): array
{
    return [
        'telegram' => TelegramChannel::class,
    ];
}

Change log

Please see CHANGELOG for more information on what has changed recently.

Testing

$ composer test

Contributing

Please see CONTRIBUTING and CODE_OF_CONDUCT for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

More Repositories

1

json-parser

🧩 Zero-dependencies lazy parser to read JSON of any dimension and from any source in a memory-efficient way.
PHP
676
star
2

lazy-json

🐼 Framework-agnostic package to load JSON of any dimension and from any source into Laravel lazy collections recursively.
PHP
235
star
3

enum

🎲 Zero-dependencies PHP library to supercharge enum functionalities.
PHP
188
star
4

command-validator

Validate Laravel console commands input.
PHP
160
star
5

laravel-enum

Discontinued. Enum generator for Laravel.
PHP
136
star
6

eloquent-inspector

πŸ•΅οΈ Inspect Laravel Eloquent models to collect properties, relationships and more.
PHP
115
star
7

Workflow

Laravel 5 package to create extendible and maintainable apps by harnessing the power of pipelines.
PHP
109
star
8

query-filters

Laravel package to filter Eloquent model records based on query parameters. Fully inspired by the Laracasts episode https://laracasts.com/series/eloquent-techniques/episodes/4
PHP
84
star
9

lazy-json-pages

πŸ“œ Framework-agnostic package to load items from any paginated JSON API into a Laravel lazy collection via async HTTP requests.
PHP
82
star
10

exception-handler

Extend the Laravel exception handler to let service providers determine how custom exceptions should be handled.
PHP
60
star
11

laravel-dto

Data Transfer Object (DTO) for Laravel
PHP
55
star
12

Auth

Laravel authentication module.
PHP
49
star
13

octane-testbench

β›½ Set of utilities to test Laravel applications powered by Octane.
PHP
42
star
14

sql-dumper

Laravel package to dump SQL queries, related EXPLAIN and location in code in different formats.
PHP
23
star
15

pest-plugin-laravel-octane

β›½ Pest plugin to test Laravel applications powered by Octane.
PHP
21
star
16

json-objects

Extract objects from large JSON files, endpoints or streams while saving memory.
PHP
20
star
17

dto

Data Transfer Object (DTO).
PHP
16
star
18

Transformer

Framework agnostic package to transform objects and arrays by manipulating, casting and mapping their properties.
PHP
14
star
19

Sublime-Text-PHP-and-Laravel-Snippets

Sublime Text snippets to ease development with PHP and Laravel.
13
star
20

console-tasker

🦾 Laravel package to create lean, powerful, idempotent and beautiful Artisan commands.
PHP
10
star
21

workflow-demo

Demo for Workflow repository
CSS
9
star
22

Date

Framework agnostic and easy to use tool to work with dates.
PHP
6
star
23

start

Mac service written in Automator to run several softwares and commands by pressing a hot key.
AppleScript
2
star
24

fluent-api

Framework agnostic starting point to perform fluent calls to any API.
PHP
1
star
25

Affiliate

PHP
1
star