Initial code

master 1.0.0
Julien Rosset 2 years ago
parent 5c392b0de5
commit 73fe5a5538

@ -1,3 +1,3 @@
# XXX
# PhpExceptionHelper
XXX
A helper class for exceptions

@ -1,6 +1,6 @@
{
"name": "jrosset/xxx",
"description": "XXX",
"name": "jrosset/exceptionhelper",
"description": "A helper class for exceptions",
"keywords": [ ],
"minimum-stability": "stable",
@ -15,7 +15,7 @@
},
"readme": "README.md",
"homepage": "https://git.jrosset.ovh/jrosset/XXX",
"homepage": "https://git.jrosset.ovh/jrosset/PhpExceptionHelper",
"license": "CC-BY-4.0",
"authors": [
{
@ -25,9 +25,9 @@
],
"support": {
"email": "jul.rosset@gmail.com",
"issues": "https://git.jrosset.ovh/jrosset/XXX/issues",
"wiki": "https://git.jrosset.ovh/jrosset/XXX/wiki",
"docs": "https://git.jrosset.ovh/jrosset/XXX/wiki",
"source": "https://git.jrosset.ovh/jrosset/XXX"
"issues": "https://git.jrosset.ovh/jrosset/PhpExceptionHelper/issues",
"wiki": "https://git.jrosset.ovh/jrosset/PhpExceptionHelper/wiki",
"docs": "https://git.jrosset.ovh/jrosset/PhpExceptionHelper/wiki",
"source": "https://git.jrosset.ovh/jrosset/PhpExceptionHelper"
}
}

@ -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…
Cancel
Save