parent
5c392b0de5
commit
73fe5a5538
@ -1,3 +1,3 @@
|
|||||||
# XXX
|
# PhpExceptionHelper
|
||||||
|
|
||||||
XXX
|
A helper class for exceptions
|
@ -0,0 +1,47 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace jrosset\ExceptionHelper;
|
||||||
|
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper class for exceptions
|
||||||
|
*/
|
||||||
|
abstract class ExceptionHelper {
|
||||||
|
/**
|
||||||
|
* This is an utilities class: extension permitted but private constructor to prevent instanciation
|
||||||
|
*/
|
||||||
|
private function __construct () {
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert an exception to a string
|
||||||
|
*
|
||||||
|
* @param Throwable $exception The exception
|
||||||
|
* @param bool $trace True if result must include trace
|
||||||
|
* @param bool $previous True if result must include previous exceptions
|
||||||
|
*
|
||||||
|
* @return string A string representing the exception
|
||||||
|
*/
|
||||||
|
public static function toString (Throwable $exception, bool $trace = true, bool $previous = true): string {
|
||||||
|
$traceLines = [];
|
||||||
|
if ($trace) {
|
||||||
|
$traceLines[] = "\t#0 " . $exception->getFile() . ':' . $exception->getLine();
|
||||||
|
foreach ($exception->getTrace() as $traceNumber => $traceInfo) {
|
||||||
|
$traceLines[] = "\t#" . ($traceNumber + 1)
|
||||||
|
. ' ' . ($traceInfo['class'] ?? '') . ($traceInfo['type'] ?? '') . ($traceInfo['function'] ?? '')
|
||||||
|
. ' (' . ($traceInfo['file'] ?? '') . ':' . ($traceInfo['line'] ?? '') . ')';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return 'EXCEPTION [' . get_class($exception) . '] : ' . $exception->getMessage()
|
||||||
|
. ($trace
|
||||||
|
? PHP_EOL . implode(PHP_EOL, $traceLines)
|
||||||
|
: ''
|
||||||
|
)
|
||||||
|
. ($previous && $exception->getPrevious() !== null
|
||||||
|
? PHP_EOL . 'Caused by ' . static::toString($exception->getPrevious(), $trace, $previous)
|
||||||
|
: ''
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,20 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
require_once __DIR__ . '/../vendor/autoload.php';
|
||||||
|
|
||||||
|
use jrosset\ExceptionHelper\ExceptionHelper;
|
||||||
|
|
||||||
|
function fail () {
|
||||||
|
throw new RuntimeException(
|
||||||
|
'General error',
|
||||||
|
0,
|
||||||
|
new LogicException('My logic is undeniable')
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
fail();
|
||||||
|
}
|
||||||
|
catch (Throwable $exception) {
|
||||||
|
var_dump(ExceptionHelper::toString($exception));
|
||||||
|
}
|
Loading…
Reference in New Issue