ErrorHandlingUtils.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. namespace Knuckles\Scribe\Tools;
  3. use Amp\MultiReasonException;
  4. use Symfony\Component\Console\Output\ConsoleOutput;
  5. use Symfony\Component\Console\Output\OutputInterface;
  6. class ErrorHandlingUtils
  7. {
  8. public static function dumpExceptionIfVerbose(\Throwable $e, $completelySilent = false): void
  9. {
  10. if (Flags::$shouldBeVerbose) {
  11. if ($e instanceof MultiReasonException) {
  12. self::dumpException($e->getReasons()[0]);
  13. } else {
  14. self::dumpException($e);
  15. }
  16. } else if (!$completelySilent) {
  17. if ($e instanceof MultiReasonException) {
  18. $message = join("\n", array_map(function (\Throwable $reason) {
  19. return $reason->getMessage();
  20. }, $e->getReasons()));
  21. } else {
  22. [$firstFrame, $secondFrame] = $e->getTrace();
  23. try {
  24. ['file' => $file, 'line' => $line] = $firstFrame;
  25. } catch (\Exception $_) {
  26. ['file' => $file, 'line' => $line] = $secondFrame;
  27. }
  28. $exceptionType = get_class($e);
  29. $message = $e->getMessage();
  30. $message = "$exceptionType in $file at line $line: $message";
  31. }
  32. ConsoleOutputUtils::warn($message);
  33. ConsoleOutputUtils::warn('Run this again with the --verbose flag to see the full stack trace.');
  34. }
  35. }
  36. public static function dumpException(\Throwable $e): void
  37. {
  38. $output = new ConsoleOutput(OutputInterface::VERBOSITY_VERBOSE);
  39. try {
  40. $handler = new \NunoMaduro\Collision\Handler(new \NunoMaduro\Collision\Writer(null, $output));
  41. } catch (\Exception $e) {
  42. // Version 3 used a different API
  43. // todo remove when Laravel 7 is minimum supported
  44. $handler = new \NunoMaduro\Collision\Handler(new \NunoMaduro\Collision\Writer($output));
  45. }
  46. $handler->setInspector(new \Whoops\Exception\Inspector($e));
  47. $handler->setException($e);
  48. $handler->handle();
  49. }
  50. }