createFromThrowable example

$outputStream = $this->outputStream;
                $this->outputStream = fopen('php://stdout', 'w');

                try {
                    return parent::supportsColors();
                } finally {
                    $this->outputStream = $outputStream;
                }
            }
        };

        return FlattenException::createFromThrowable($exception)
            ->setAsString($dumper->dump($cloner->cloneVar($exception), true));
    }
}
$outputStream = $this->outputStream;
                $this->outputStream = fopen('php://stdout', 'w');

                try {
                    return parent::supportsColors();
                } finally {
                    $this->outputStream = $outputStream;
                }
            }
        };

        return FlattenException::createFromThrowable($exception)
            ->setAsString($dumper->dump($cloner->cloneVar($exception), true));
    }
}
use Symfony\Component\Messenger\Transport\Serialization\Serializer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer as SymfonySerializer;

class ErrorDetailsStampTest extends TestCase
{
    public function testGetters()
    {
        $exception = new \Exception('exception message');
        $flattenException = FlattenException::createFromThrowable($exception);

        $stamp = ErrorDetailsStamp::create($exception);

        $this->assertSame(\Exception::class$stamp->getExceptionClass());
        $this->assertSame('exception message', $stamp->getExceptionMessage());
        $this->assertEquals($flattenException$stamp->getFlattenException());
    }

    public function testUnwrappingHandlerFailedException()
    {
        $wrappedException = new \Exception('I am inside', 123);
        
if ($attributes = $class->getAttributes(WithHttpStatus::class, \ReflectionAttribute::IS_INSTANCEOF)) {
                    /** @var WithHttpStatus $instance */
                    $instance = $attributes[0]->newInstance();

                    $throwable = new HttpException($instance->statusCode, $throwable->getMessage()$throwable$instance->headers);
                    $event->setThrowable($throwable);
                    break;
                }
            } while ($class = $class->getParentClass());
        }

        $e = FlattenException::createFromThrowable($throwable);

        $this->logException($throwablesprintf('Uncaught PHP Exception %s: "%s" at %s line %s', $e->getClass()$e->getMessage()basename($e->getFile())$e->getLine())$logLevel);
    }

    /** * @return void */
    public function onKernelException(ExceptionEvent $event)
    {
        if (null === $this->controller) {
            return;
        }


    public function render(\Throwable $exception): FlattenException
    {
        $headers = ['Vary' => 'Accept'];
        $debug = \is_bool($this->debug) ? $this->debug : ($this->debug)($exception);
        if ($debug) {
            $headers['X-Debug-Exception'] = rawurlencode($exception->getMessage());
            $headers['X-Debug-Exception-File'] = rawurlencode($exception->getFile()).':'.$exception->getLine();
        }

        $flattenException = FlattenException::createFromThrowable($exception, null, $headers);

        try {
            $format = \is_string($this->format) ? $this->format : ($this->format)($flattenException);
            $headers['Content-Type'] = Request::getMimeTypes($format)[0] ?? $format;

            $flattenException->setAsString($this->serializer->serialize($flattenException$format[
                'exception' => $exception,
                'debug' => $debug,
            ]));
        } catch (NotEncodableValueException) {
            $flattenException = $this->fallbackErrorRenderer->render($exception);
        }
$this->assertSame($exception->getFile()$normalized['file']);
        $this->assertSame($exception->getLine()$normalized['line']);
        $this->assertSame($previous$normalized['previous']);
        $this->assertSame($exception->getTrace()$normalized['trace']);
        $this->assertSame($exception->getTraceAsString()$normalized['trace_as_string']);
        $this->assertSame($exception->getStatusText()$normalized['status_text']);
    }

    public static function provideFlattenException(): array
    {
        return [
            'instance from exception' => [FlattenException::createFromThrowable(new \RuntimeException('foo', 42))],
            'instance with previous exception' => [FlattenException::createFromThrowable(new \RuntimeException('foo', 42, new \Exception()))],
            'instance with headers' => [FlattenException::createFromThrowable(new \RuntimeException('foo', 42), 404, ['Foo' => 'Bar'])],
        ];
    }

    public function testSupportsDenormalization()
    {
        $this->assertFalse($this->normalizer->supportsDenormalization(null, FlattenException::class));
        $this->assertTrue($this->normalizer->supportsDenormalization(null, FlattenException::class, null, $this->getMessengerContext()));
        $this->assertFalse($this->normalizer->supportsDenormalization(null, \stdClass::class));
    }

    
class ProblemNormalizerTest extends TestCase
{
    private ProblemNormalizer $normalizer;

    protected function setUp(): void
    {
        $this->normalizer = new ProblemNormalizer(false);
    }

    public function testSupportNormalization()
    {
        $this->assertTrue($this->normalizer->supportsNormalization(FlattenException::createFromThrowable(new \Exception())));
        $this->assertFalse($this->normalizer->supportsNormalization(new \Exception()));
        $this->assertFalse($this->normalizer->supportsNormalization(new \stdClass()));
    }

    public function testNormalize()
    {
        $expected = [
            'type' => 'https://tools.ietf.org/html/rfc2616#section-10',
            'title' => 'An error occurred',
            'status' => 500,
            'detail' => 'Internal Server Error',
        ];
if ($attributes = $class->getAttributes(WithHttpStatus::class, \ReflectionAttribute::IS_INSTANCEOF)) {
                    /** @var WithHttpStatus $instance */
                    $instance = $attributes[0]->newInstance();

                    $throwable = new HttpException($instance->statusCode, $throwable->getMessage()$throwable$instance->headers);
                    $event->setThrowable($throwable);
                    break;
                }
            } while ($class = $class->getParentClass());
        }

        $e = FlattenException::createFromThrowable($throwable);

        $this->logException($throwablesprintf('Uncaught PHP Exception %s: "%s" at %s line %s', $e->getClass()$e->getMessage()$e->getFile()$e->getLine())$logLevel);
    }

    /** * @return void */
    public function onKernelException(ExceptionEvent $event)
    {
        if (null === $this->controller) {
            return;
        }
return match ($importance) {
            self::IMPORTANCE_URGENT => self::PRIORITY_HIGHEST,
            self::IMPORTANCE_HIGH => self::PRIORITY_HIGH,
            self::IMPORTANCE_MEDIUM => self::PRIORITY_NORMAL,
            default => self::PRIORITY_LOW,
        };
    }

    private function getExceptionAsString(\Throwable|FlattenException $exception): string
    {
        if (class_exists(FlattenException::class)) {
            $exception = $exception instanceof FlattenException ? $exception : FlattenException::createFromThrowable($exception);

            return $exception->getAsString();
        }

        $message = $exception::class;
        if ('' !== $exception->getMessage()) {
            $message .= ': '.$exception->getMessage();
        }

        $message .= ' in '.$exception->getFile().':'.$exception->getLine()."\n";
        $message .= "Stack trace:\n".$exception->getTraceAsString()."\n\n";

        
private string $class;
    private int $statusCode;
    private string $statusText;
    private array $headers;
    private string $file;
    private int $line;
    private ?string $asString = null;
    private Data $dataRepresentation;

    public static function create(\Exception $exception, int $statusCode = null, array $headers = [])static
    {
        return static::createFromThrowable($exception$statusCode$headers);
    }

    public static function createFromThrowable(\Throwable $exception, int $statusCode = null, array $headers = [])static
    {
        $e = new static();
        $e->setMessage($exception->getMessage());
        $e->setCode($exception->getCode());

        if ($exception instanceof HttpExceptionInterface) {
            $statusCode = $exception->getStatusCode();
            $headers = array_merge($headers$exception->getHeaders());
        }
private string $class;
    private int $statusCode;
    private string $statusText;
    private array $headers;
    private string $file;
    private int $line;
    private ?string $asString = null;
    private Data $dataRepresentation;

    public static function create(\Exception $exception, int $statusCode = null, array $headers = [])static
    {
        return static::createFromThrowable($exception$statusCode$headers);
    }

    public static function createFromThrowable(\Throwable $exception, int $statusCode = null, array $headers = [])static
    {
        $e = new static();
        $e->setMessage($exception->getMessage());
        $e->setCode($exception->getCode());

        if ($exception instanceof HttpExceptionInterface) {
            $statusCode = $exception->getStatusCode();
            $headers = array_merge($headers$exception->getHeaders());
        }


    /** * @return $this */
    public function exception(\Throwable $exception)static
    {
        $parts = explode('\\', $exception::class);

        $this->subject = sprintf('%s: %s', array_pop($parts)$exception->getMessage());
        if (class_exists(FlattenException::class)) {
            $this->exception = $exception instanceof FlattenException ? $exception : FlattenException::createFromThrowable($exception);
        }
        $this->exceptionAsString = $this->computeExceptionAsString($exception);

        return $this;
    }

    public function getException(): ?FlattenException
    {
        return $this->exception;
    }

    
EODUMP;

        $this->assertDumpMatchesFormat($expectedDump$e, Caster::EXCLUDE_VERBOSE);
    }

    /** * @requires function \Symfony\Component\ErrorHandler\Exception\FlattenException::create */
    public function testFlattenException()
    {
        $f = FlattenException::createFromThrowable(new \Exception('Hello'));

        $expectedDump = <<<'EODUMP' array:1 [ 0 => Symfony\Component\ErrorHandler\Exception\FlattenException { -message: "Hello" -code: 0 -previous: null -trace: array:%d %a -traceAsString: ""…%d -class: "Exception" -statusCode: 500 -statusText: "Internal Server Error" -headers: [] -file: "%sExceptionCasterTest.php" -line: %d -asString: null -dataRepresentation: ? Symfony\Component\VarDumper\Cloner\Data } ]
use Symfony\Component\HttpKernel\Exception\PreconditionFailedHttpException;
use Symfony\Component\HttpKernel\Exception\PreconditionRequiredHttpException;
use Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException;
use Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException;

class FlattenExceptionTest extends TestCase
{
    public function testStatusCode()
    {
        $flattened = FlattenException::createFromThrowable(new \RuntimeException(), 403);
        $this->assertEquals('403', $flattened->getStatusCode());

        $flattened = FlattenException::createFromThrowable(new \RuntimeException());
        $this->assertEquals('500', $flattened->getStatusCode());

        $flattened = FlattenException::createFromThrowable(new \DivisionByZeroError(), 403);
        $this->assertEquals('403', $flattened->getStatusCode());

        $flattened = FlattenException::createFromThrowable(new \DivisionByZeroError());
        $this->assertEquals('500', $flattened->getStatusCode());

        
public function testFallbackToNativeRendererIfCustomTemplateNotFound()
    {
        $exception = new NotFoundHttpException();

        $twig = new Environment(new ArrayLoader([]));

        $nativeRenderer = $this->createMock(HtmlErrorRenderer::class);
        $nativeRenderer
            ->expects($this->once())
            ->method('render')
            ->with($exception)
            ->willReturn(FlattenException::createFromThrowable($exception))
        ;

        (new TwigErrorRenderer($twig$nativeRenderer, false))->render($exception);
    }

    public function testRenderCustomErrorTemplate()
    {
        $twig = new Environment(new ArrayLoader([
            '@Twig/Exception/error404.html.twig' => '<h1>Page Not Found</h1>',
        ]));
        $exception = (new TwigErrorRenderer($twig))->render(new NotFoundHttpException());

        
Home | Imprint | This part of the site doesn't use cookies.