README.md 1.89 KB
Newer Older
Jan Kuchař's avatar
Jan Kuchař committed
1 2
# Suppressed exceptions for PHP

Jan Kuchař's avatar
Jan Kuchař committed
3
Suppressed exceptions are useful for aggregating more exceptions from unreliable resources.
Jan Kuchař's avatar
Jan Kuchař committed
4

Jan Kuchař's avatar
Jan Kuchař committed
5 6
Useful when you want to communicate that process failed, with a list of sibling exceptions that led to an error.

Jan Kuchař's avatar
Jan Kuchař committed
7 8
repositories:  
- [Grifart GitLab](https://gitlab.grifart.cz/grifart/suppressed-exceptions) [![pipeline status](https://gitlab.grifart.cz/grifart/suppressed-exceptions/badges/master/pipeline.svg)](https://gitlab.grifart.cz/grifart/suppressed-exceptions/commits/master)
Jan Kuchař's avatar
Jan Kuchař committed
9
- [GitHub](https://github.com/grifart/suppressed-exceptions) (mirror) [![Build Status](https://travis-ci.org/grifart/suppressed-exceptions.svg?branch=master)](https://travis-ci.org/grifart/suppressed-exceptions)
Jan Kuchař's avatar
Jan Kuchař committed
10

Jan Kuchař's avatar
Jan Kuchař committed
11
## Example usage
Jan Kuchař's avatar
Jan Kuchař committed
12 13 14 15 16 17 18

```php
$remoteSources = []; // classes representing unreliable remote sources

$exceptions = [];
foreach ($remoteSoures as $remoteSource) {
	try {
Jan Kuchař's avatar
Jan Kuchař committed
19
		$remoteSource->fetch(); // unsafe operation
Jan Kuchař's avatar
Jan Kuchař committed
20 21 22 23 24 25
	} catch (FetchingFailed $e) {
		$exceptions[] = $e;
		continue;
	}
}

Jan Kuchař's avatar
Jan Kuchař committed
26
if (count($exceptions) > 0) {
Jan Kuchař's avatar
Jan Kuchař committed
27 28 29 30
	$e = new ProcessingFailed();
	$e->addSuppressed(...$exceptions);
	throw $e;
}
Jan Kuchař's avatar
Jan Kuchař committed
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
```

You can also override exception constructor to provide better API

```php
final class EventPropagationFailedException extends \RuntimeException implements \Grifart\SuppressedExceptions\WithSuppressedExceptions
{
	use \Grifart\SuppressedExceptions\SuppressedExceptions;

	public function __construct(\Throwable ...$suppressed)
	{
		parent::__construct('Saving succeeded, but some listeners failed to complete their job. Please check suppressed exceptions for more information.');
		$this->addSuppressed(...$suppressed);
	}
}
```

Usage is then

```php
throw new EventPropagationFailedException(...$suppressedExceptions);
```


**TODO: screenshot from debugger** how it looks when catched



## More reading

- https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html#suppressed-exceptions

Jan Kuchař's avatar
Jan Kuchař committed
63