PHPackages                             code-distortion/clarity-control - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Logging &amp; Monitoring](/categories/logging)
4. /
5. code-distortion/clarity-control

ActiveLibrary[Logging &amp; Monitoring](/categories/logging)

code-distortion/clarity-control
===============================

A Laravel package to catch and log exceptions with a fluent interface

0.1.0(2y ago)01.3kMITPHPPHP 8.0.\* | 8.1.\* | 8.2.\* | 8.3.\*CI failing

Since Dec 31Pushed 2y ago1 watchersCompare

[ Source](https://github.com/code-distortion/clarity-control)[ Packagist](https://packagist.org/packages/code-distortion/clarity-control)[ Docs](https://github.com/code-distortion/clarity-control)[ RSS](/packages/code-distortion-clarity-control/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (7)Versions (2)Used By (0)

Clarity Control - Handle Your Exceptions
========================================

[](#clarity-control---handle-your-exceptions)

[![Latest Version on Packagist](https://camo.githubusercontent.com/c150fcb28d22fe00c96a14be1328e89c0769befcc2686c16cde87028b7afe361/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f636f64652d646973746f7274696f6e2f636c61726974792d636f6e74726f6c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/code-distortion/clarity-control)[![PHP Version](https://camo.githubusercontent.com/4359263e89771845b086ad2c059d7df9d332722f977037512184fa9dea74dfb2/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e30253230746f253230382e332d626c75653f7374796c653d666c61742d737175617265)](https://camo.githubusercontent.com/4359263e89771845b086ad2c059d7df9d332722f977037512184fa9dea74dfb2/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e30253230746f253230382e332d626c75653f7374796c653d666c61742d737175617265)[![Laravel](https://camo.githubusercontent.com/8ae51e76c8f9d6f0949d69e776278cce40f6dccdbb4ac57baae97b7beb4b12a1/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c61726176656c2d38253230746f25323031302d626c75653f7374796c653d666c61742d737175617265)](https://camo.githubusercontent.com/8ae51e76c8f9d6f0949d69e776278cce40f6dccdbb4ac57baae97b7beb4b12a1/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c61726176656c2d38253230746f25323031302d626c75653f7374796c653d666c61742d737175617265)[![GitHub Workflow Status](https://camo.githubusercontent.com/a418be837826d9739c04ba1e7314925d8b1b7f552c907641d5ad6dd283dc05f1/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f636f64652d646973746f7274696f6e2f636c61726974792d636f6e74726f6c2f72756e2d74657374732e796d6c3f6272616e63683d6d6173746572267374796c653d666c61742d737175617265)](https://github.com/code-distortion/clarity-control/actions)[![Buy The World a Tree](https://camo.githubusercontent.com/dc3f77a9b22c3bc83c7b7d863bf138a7ca3418f1826b0b16d073d0aa87c16bc4/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f74726565776172652d2546302539462538432542332d6c69676874677265656e3f7374796c653d666c61742d737175617265)](https://plant.treeware.earth/code-distortion/clarity-control)[![Contributor Covenant](https://camo.githubusercontent.com/902d296a65b2997bada7e7717fd929d9177f3bd95414cbb5ea2ed843c680f314/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f636f6e7472696275746f72253230636f76656e616e742d76322e3125323061646f707465642d6666363962342e7376673f7374796c653d666c61742d737175617265)](.github/CODE_OF_CONDUCT.md)

***code-distortion/clarity-control*** is a Laravel package that lets you catch and log exceptions with a fluent interface.

```
// run $callable - will catch + report() any exceptions
Control::run($callable);

// do the same, but with extra optional configuration
Control::prepare($callable)
    ->channel('slack')
    ->level(Settings::REPORTING_LEVEL_WARNING)
    ->debug() … ->emergency()
    ->default('some-value')
    ->catch(DivisionByZeroError::class)
    ->match('Undefined variable $a')
    ->matchRegex('/^Undefined variable /')
    ->known('https://company.atlassian.net/browse/ISSUE-1234')
    ->report() or ->dontReport()
    ->rethrow() or ->dontRethrow() or ->rethrow($callable)
    ->callback($callable)
    ->finally($callable)
    ->execute();
```

Clarity Suite
-------------

[](#clarity-suite)

Clarity Control is a part of the ***Clarity Suite***, designed to let you manage exceptions more easily:

- [Clarity Context](https://github.com/code-distortion/clarity-context) - Understand Your Exceptions
- [Clarity Logger](https://github.com/code-distortion/clarity-logger) - Useful Exception Logs
- **Clarity Control** - Handle Your Exceptions

Table of Contents
-----------------

[](#table-of-contents)

- [Installation](#installation)
    - [Config File](#config-file)
- [Catching Exceptions](#catching-exceptions)
- [Configuring The Way Exceptions Are Caught](#configuring-the-way-exceptions-are-caught)
    - [Note About Logging](#note-about-logging)
- [Log Channel](#log-channel)
- [Log Level](#log-level)
- [Default Return Value](#default-return-value)
- [Catching Selectively](#catching-selectively)
- [Recording "Known" Issues](#recording-known-issues)
- [Disabling Logging](#disabling-logging)
- [Re-throwing Exceptions](#re-throwing-exceptions)
- [Suppressing Exceptions](#suppressing-exceptions)
- [Callbacks](#callbacks)
    - [Using The Context Object in Callbacks](#using-the-context-object-in-callbacks)
    - [Suppressing Exceptions On The Fly](#suppressing-exceptions-on-the-fly)
    - [Global Callbacks](#global-callbacks)
- [Advanced Catching](#advanced-catching)
- [Retrieving Exceptions](#retrieving-exceptions)

Installation
------------

[](#installation)

Install the package via composer:

```
composer require code-distortion/clarity-control
```

### Config File

[](#config-file)

Use the following command if you would like to publish the `config/code_distortion.clarity_control.php` config file:

```
php artisan vendor:publish --provider="CodeDistortion\ClarityControl\ServiceProvider" --tag="config"
```

Catching Exceptions
-------------------

[](#catching-exceptions)

Clarity Control deals with flow control. Which is to say, it provides ways to catch and manage exceptions.

Whilst you can still use [try / catch statements](https://www.php.net/manual/en/language.exceptions.php) of course, you can write them this way instead:

```
use CodeDistortion\ClarityControl\Control;

Control::run($callable);

// is equivalent to:
try {
    $callable(); // … do something
} catch (Exception $e) {
    report($e);
}
```

Control will run the *callable* passed to `Control::run(…)`. If an exception occurs, it will be caught and reported using Laravel's `report()` helper.

The code following it will continue to run afterwards.

> ***Tip:*** [Laravel's *dependency injection*](https://laravel.com/docs/10.x/container#when-to-use-the-container) system is used to run your callable. Just type-hint your parameters and they'll be resolved for you.

Configuring The Way Exceptions Are Caught
-----------------------------------------

[](#configuring-the-way-exceptions-are-caught)

Another way to write this is to call `Control::prepare($callable)`, and then `->execute()` afterwards.

```
use CodeDistortion\ClarityControl\Control;

Control::prepare($callable)->execute();
// is equivalent to:
Control::run($callable);
```

These are the same, except that when using `Control::prepare($callable)` and `->execute()`, there's an opportunity to set some configuration values in-between…

Here is the list of the methods you can use to configure the way Control catches exceptions (they're explained in more detail below):

```
use CodeDistortion\ClarityControl\Control;
use CodeDistortion\ClarityControl\Settings;

Control::prepare($callable)
    ->channel('slack')
    ->level(Settings::REPORTING_LEVEL_WARNING)
    ->debug() … ->emergency()
    ->default('default')
    ->catch(DivisionByZeroError::class)
    ->match('Undefined variable $a')
    ->matchRegex('/^Undefined variable /')
    ->known('https://company.atlassian.net/browse/ISSUE-1234')
    ->report() or ->dontReport()
    ->rethrow() or ->dontRethrow() or ->rethrow($callable)
    ->callback($callable)
    ->finally($callable)
    ->execute();
```

### Note About Logging

[](#note-about-logging)

This package uses [Clarity Context](https://github.com/code-distortion/clarity-context#logging-exceptions), and some settings require a logger that's also aware of *Clarity Context* (such as [Clarity Logger](https://github.com/code-distortion/clarity-logger)) to work. Specifically, the *channel*, *log level*, and *"known" issue* settings won't appear anywhere otherwise.

These details are added to the `Context` object that *Clarity Context* produces when an exception occurs. And it's up to the logger to use its values.

See [Clarity Context](https://github.com/code-distortion/clarity-context#logging-exceptions) for more information about this `Context` object.

See [Clarity Logger](https://github.com/code-distortion/clarity-logger) for a logger that understands the `Context` object.

Log Channel
-----------

[](#log-channel)

You can specify which Laravel log-channel you'd like to log to. The possible values come from your projects' `config/logging.php` file.

```
Control::prepare($callable)->channel('slack')->execute();
```

You can specify more than one if you'd like.

```
Control::prepare($callable)->channel(['stack', 'slack'])->execute();
```

> ***Note:*** This setting requires a logging tool that's aware of Clarity. See the [Note About Logging](#note-about-logging) for more information.

> See [Laravel's documentation about logging](https://laravel.com/docs/10.x/logging#available-channel-drivers) for more information about Log Channels.

Log Level
---------

[](#log-level)

You can specify the reporting level you'd like to use when logging.

```
use CodeDistortion\ClarityControl\Settings;

Control::prepare($callable)->debug()->execute();
Control::prepare($callable)->info()->execute();
Control::prepare($callable)->notice()->execute();
Control::prepare($callable)->warning()->execute();
Control::prepare($callable)->error()->execute();
Control::prepare($callable)->critical()->execute();
Control::prepare($callable)->alert()->execute();
Control::prepare($callable)->emergency()->execute();
// or
Control::prepare($callable)->level(Settings::REPORTING_LEVEL_WARNING)->execute(); // etc
```

> ***Note:*** This setting requires a logging tool that's aware of Clarity. See the [Note About Logging](#note-about-logging) for more information.

> See [Laravel's documentation about logging](https://laravel.com/docs/10.x/logging#writing-log-messages) for more information about Log Levels.

Default Return Value
--------------------

[](#default-return-value)

You can specify the default value to return when an exception occurs by passing a second parameter to `Control::run()` or `Control::prepare()`.

```
$result = Control::run($callable, $default);
// or
$result = Control::prepare($callable, $default)->execute();
```

You can also call `->default()` after calling `Control::prepare()`

```
$result = Control::prepare($callable)->default($default)->execute();
```

> ***Tip:*** If the default value is *callable*, Control will run it (when needed) to resolve the value.

Catching Selectively
--------------------

[](#catching-selectively)

You can choose to only catch certain types of exceptions. Other exceptions will ignored.

```
use DivisionByZeroError;

Control::prepare($callable)
    ->catch(DivisionByZeroError::class) // only catch this type of exception
    ->execute();
```

```
Control::prepare($callable)
    ->match('Undefined variable $a')       // exact string match of $e->getMessage()
    ->matchRegex('/^Undefined variable /') // regex string match of $e->getMessage()
    ->execute();
```

You can specify multiple exception classes, match-strings or regexes.

When you specify `match()` and `matchRegex()`, only one of them needs to match the exception message.

Recording "Known" Issues
------------------------

[](#recording-known-issues)

If you use an issue management system like Jira, you can make a note of the issue/task the exception relates to:

```
Control::prepare($callable)
    ->known('https://company.atlassian.net/browse/ISSUE-1234')
    ->execute();
```

This gives you an opportunity to label exceptions while the fix is being worked on.

> ***Note:*** This setting requires a logging tool that's aware of Clarity. See the [Note About Logging](#note-about-logging) for more information.

Disabling Logging
-----------------

[](#disabling-logging)

You can disable the reporting of exceptions once caught. This will stop `report()` from being triggered.

```
Control::prepare($callable)->dontReport()->execute();
// or
Control::prepare($callable)->report(false)->execute();
```

Re-throwing Exceptions
----------------------

[](#re-throwing-exceptions)

If you'd like caught exceptions to be detected and reported, but *re-thrown* again afterwards, you can tell Control to rethrow them:

```
Control::prepare($callable)->rethrow()->execute();
```

If you'd like to rethrow a different exception, you can pass a closure to make the decision. It must return a Throwable / Exception, or true / false.

```
$closure = fn(Throwable $e) => new MyException('Something happened', 0, $e);
Control::prepare($callable)->rethrow($closure)->execute();
```

Suppressing Exceptions
----------------------

[](#suppressing-exceptions)

If you'd like to stop exceptions from being reported *and* rethrown once caught, you can suppress them altogether.

```
Control::prepare($callable)->suppress()->execute();
// is equivalent to:
Control::prepare($callable)->dontReport()->dontRethrow()->execute();
```

Callbacks
---------

[](#callbacks)

You can add a custom callback to be run when an exception is caught. This can be used to either *do something* when an exception occurs, or to decide if the [the exception should be "suppressed"](#suppressing-exceptions).

You can add multiple callbacks if you like.

```
use CodeDistortion\ClarityControl\Context;
use Illuminate\Http\Request;
use Throwable;

$callback = fn(Throwable $e, Context $context, Request $request) => …; // do something

Control::prepare($callable)->callback($callback)->execute();
```

> ***Tip:*** [Laravel's *dependency injection*](https://laravel.com/docs/10.x/container#when-to-use-the-container) is used to run your callback. Just type-hint your parameters, like in the example above.
>
> Extra parameters you can use are:
>
> - The exception: when the parameter is named `$e` or `$exception`
> - The `Context` object: when type-hinted with `CodeDistortion\ClarityContext\Context`

### Using The Context Object in Callbacks

[](#using-the-context-object-in-callbacks)

When you type-hint a callback parameter with `CodeDistortion\ClarityContext\Context`, you'll receive the `Context` object populated with details about the exception.

This is the *same* Context object from the [Clarity Context](https://github.com/code-distortion/clarity-context) package, and is designed to be used in `app/Exceptions/Handler.php` when reporting an exception. See Clarity Context's [documentation for more information](https://github.com/code-distortion/clarity-context#logging-exceptions).

As well as reading values from the Context object, you can update some of its values inside your callback. This lets you alter what happens on-the-fly.

```
use CodeDistortion\ClarityControl\Context;
use CodeDistortion\ClarityControl\Settings;

$callback = function (Context $context) {
    // the exception that occurred
    $context->getException();
    // manage the log channels
    $context->getChannels();
    $context->setChannels(['slack']);
    // manage the log reporting level
    $context->getLevel();
    $context->setLevel(Settings::REPORTING_LEVEL_WARNING);
    $context->debug() … $context->emergency();
    // manage the default return value
    $context->getDefault();
    $context->setDefault('default');
    // manage the request's trace identifiers
    $context->getTraceIdentifiers();
    $context->setTraceIdentifiers([$traceId]);
    // manage the known issues
    $context->hasKnown();
    $context->getKnown();
    $context->setKnown(['https://company.atlassian.net/browse/ISSUE-1234']);
    // manage the report setting
    $context->getReport();
    $context->setReport(true/false);
    $context->dontReport();
    // manage the rethrow setting
    $context->getRethrow();
    $context->setRethrow(true/false);
    $context->setRethrow($exception); // a new exception to rethrow
    $context->setRethrow($callable);  // a closure that decides which exception to rethrow
    $context->dontRethrow();
    // turn both report and rethrow off
    $context->suppress();
};
```

### Suppressing Exceptions On The Fly

[](#suppressing-exceptions-on-the-fly)

You can suppress an exception by calling `$context->suppress()` inside your callback.

This will also happen if your callback sets `$context->setReport(false)` *and* `$context->setRethrow(false)`.

> ***Tip:*** Callbacks are run in the order they were specified. Subsequent callbacks won't be called when the exception is suppressed.

```
use CodeDistortion\ClarityControl\Context;
use Illuminate\Http\Request;

$callback = function (Context $context, Request $request) {

    // suppress the exception when the user-agent is 'test-agent'
    if ($request->userAgent == 'test-agent') {
        $context->suppress()
        // or
        $context->setReport(false)->setRethrow(false);
    }
};

Control::prepare($callable)->callback($callback)->execute();
```

### Global Callbacks

[](#global-callbacks)

You can tell Control to run a "global" callback whenever it catches an exception. You can add as many as you need.

These callbacks are run *before* the regular (non-global) callbacks.

```
Control::globalCallback($callable);
```

A good place to set one up would be in a service provider. See Laravel's documentation for [more information about service providers](https://laravel.com/docs/10.x/providers#main-content).

```
namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use CodeDistortion\ClarityControl\Control;

class MyServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $callback = function () { … }; // do something
        Control::globalCallback($callback); // execute();
```

You can also call `->finally()` after calling `Control::prepare()`

```
Control::prepare($callable)->finally($finally)->execute();
```

> ***Tip:*** [Laravel's *dependency injection*](https://laravel.com/docs/10.x/container#when-to-use-the-container) system is used to run your callable. Just type-hint your parameters and they'll be resolved for you.

Advanced Catching
-----------------

[](#advanced-catching)

You can choose to do different things when different exceptions are caught.

To do this, configure a `CodeDistortion\ClarityControl\CatchType` object, and pass *that* to `$clarity->catch()` instead of passing the exception class *string*.

`CatchType` objects can be customised with the same settings as the `Control` object. They're all optional, and can be called in any order.

```
use CodeDistortion\ClarityControl\CatchType;
use CodeDistortion\ClarityControl\Settings;

$catchType1 = CatchType::channel('slack')
    ->level(Settings::REPORTING_LEVEL_WARNING)
    ->debug() … ->emergency()
    ->default('default')
    ->catch(DivisionByZeroError::class)
    ->match('Undefined variable $a')
    ->matchRegex('/^Undefined variable /')
    ->known('https://company.atlassian.net/browse/ISSUE-1234')
    ->report() or ->dontReport()
    ->rethrow() or ->dontRethrow() or ->rethrow($callable)
    ->suppress()
    ->callback($callable)
    ->finally($callable);
$catchType2 = …;

Control::prepare($callable)
    ->catch($catchType1)
    ->catch($catchType2)
    ->execute();
```

CatchTypes are checked in the order they were specified. The first one that matches the exception is used.

Retrieving Exceptions
---------------------

[](#retrieving-exceptions)

If you'd like to obtain the exception, you can call `getException()` and pass a variable by reference. When an exception occurs, it will contain the exception afterwards. Otherwise it's set to *null*.

The exception will be set, even if the exception was [suppressed](#suppressing-exceptions).

```
Control::prepare($callable)->getException($e)->execute();

dump($e); // will contain the exception, or null
```

Testing This Package
--------------------

[](#testing-this-package)

- Clone this package: `git clone https://github.com/code-distortion/clarity-control.git .`
- Run `composer install` to install dependencies
- Run the tests: `composer test`

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

### SemVer

[](#semver)

This library uses [SemVer 2.0.0](https://semver.org/) versioning. This means that changes to `X` indicate a breaking change: `0.0.X`, `0.X.y`, `X.y.z`. When this library changes to version 1.0.0, 2.0.0 and so forth, it doesn't indicate that it's necessarily a notable release, it simply indicates that the changes were breaking.

Treeware
--------

[](#treeware)

This package is [Treeware](https://treeware.earth). If you use it in production, then we ask that you [**buy the world a tree**](https://plant.treeware.earth/code-distortion/clarity-control) to thank us for our work. By contributing to the Treeware forest you’ll be creating employment for local families and restoring wildlife habitats.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](.github/CONTRIBUTING.md) for details.

### Code of Conduct

[](#code-of-conduct)

Please see [CODE\_OF\_CONDUCT](.github/CODE_OF_CONDUCT.md) for details.

### Security

[](#security)

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

Credits
-------

[](#credits)

- [Tim Chandler](https://github.com/code-distortion)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

24

—

LowBetter than 32% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity14

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity46

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

861d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/5c2faa0204914f71abdbae72c3c12b86fb33a1dce0254e592109411a5b4689a3?d=identicon)[code-distortion](/maintainers/code-distortion)

---

Top Contributors

[![code-distortion](https://avatars.githubusercontent.com/u/56794290?v=4)](https://github.com/code-distortion "code-distortion (1 commits)")

---

Tags

loglaravelexceptionerrorContextreportcatch

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/code-distortion-clarity-control/health.svg)

```
[![Health](https://phpackages.com/badges/code-distortion-clarity-control/health.svg)](https://phpackages.com/packages/code-distortion-clarity-control)
```

###  Alternatives

[guanguans/laravel-exception-notify

Monitor exception and report to the notification channels(Log、Mail、AnPush、Bark、Chanify、DingTalk、Discord、Gitter、GoogleChat、IGot、Lark、Mattermost、MicrosoftTeams、NowPush、Ntfy、Push、Pushback、PushBullet、PushDeer、PushMe、Pushover、PushPlus、QQ、RocketChat、ServerChan、ShowdocPush、SimplePush、Slack、Telegram、WeWork、WPush、XiZhi、YiFengChuanHua、ZohoCliq、ZohoCliqWebHook、Zulip).

14642.7k1](/packages/guanguans-laravel-exception-notify)[larabug/larabug

Laravel 6.x/7.x/8.x/9.x/10.x/11.x/12.x/13.x bug notifier

299549.3k1](/packages/larabug-larabug)[yaro/log-envelope

Laravel 5 email on error

4147.0k](/packages/yaro-log-envelope)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
