parent
20e6bf135d
commit
012c84655d
@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace jrosset\LastErrorException;
|
||||
|
||||
use ErrorException;
|
||||
|
||||
/**
|
||||
* Exception based on {@see https://www.php.net/manual/function.error-get-last.php error_get_last()}
|
||||
*/
|
||||
class LastErrorException extends ErrorException {
|
||||
/**
|
||||
* Constructs the exception
|
||||
*
|
||||
* @param int $code The exception code
|
||||
*/
|
||||
public function __construct (int $code = 0) {
|
||||
if (($lastError = error_get_last()) === null) {
|
||||
$lastError = [
|
||||
'type' => 0,
|
||||
'message' => '',
|
||||
'file' => __FILE__,
|
||||
'line' => __LINE__,
|
||||
];
|
||||
}
|
||||
parent::__construct($lastError['message'], $code, $lastError['type'], $lastError['file'], $lastError['line']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the exception if there is a last error
|
||||
*
|
||||
* @param bool $checkErrorReporting Check if last error type match {@see https://www.php.net/manual/function.error-reporting error_reporting()}
|
||||
*
|
||||
* @return static|null The exception or Null if no last error
|
||||
*/
|
||||
public static function createFromLastError (bool $checkErrorReporting = true): ?static {
|
||||
if (($lastError = error_get_last()) === null) {
|
||||
return null;
|
||||
}
|
||||
if ($checkErrorReporting && !($lastError['type'] & error_reporting())) {
|
||||
return null;
|
||||
}
|
||||
return new static();
|
||||
}
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
use jrosset\LastErrorException\LastErrorException;
|
||||
|
||||
require_once __DIR__ . '/../vendor/autoload.php';
|
||||
|
||||
try {
|
||||
if (!file_put_contents('/test_file', 'Some data')) {
|
||||
throw LastErrorException::createFromLastError();
|
||||
}
|
||||
}
|
||||
catch (Throwable $e) {
|
||||
fwrite(
|
||||
STDERR,
|
||||
'EXCEPTION [' . get_class($e) . '] ' . $e->getMessage()
|
||||
. PHP_EOL . 'in ' . $e->getFile() . '(' . $e->getLine() . ')'
|
||||
. PHP_EOL . $e->getTraceAsString()
|
||||
);
|
||||
}
|
Loading…
Reference in New Issue