PHP code example of meritum / http-exception-handler

1. Go to this page and download the library: Download meritum/http-exception-handler library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

meritum / http-exception-handler example snippets


use Meritum\HttpExceptionHandler\ExceptionHandlerModule;
use Meritum\StructuredLogging\StructuredLoggingModule;

$kernel->define(LoggerInterface::class, fn() => new MyLogger());
$kernel->addModule(new StructuredLoggingModule());
$kernel->addModule(new ExceptionHandlerModule());
$kernel->boot();

use Meritum\Http\Exception\HttpException;

final class ResourceNotFoundException extends HttpException
{
    protected string $title = 'Not Found';
    protected int $status = 404;
}

throw new ResourceNotFoundException($request, 'User 42 does not exist.');

use Throwable;
use Meritum\StructuredLogging\TranslationHandler;
use Meritum\StructuredLogging\Exception\DomainException;

final class ValidationExceptionTranslationHandler implements TranslationHandler
{
    public function matches(Throwable $exception): bool
    {
        return $exception instanceof ValidationHttpException;
    }

    public function handle(Throwable $exception): DomainException
    {
        assert($exception instanceof ValidationHttpException);

        return new ValidationDomainException($exception);
    }

    public function priority(): int
    {
        return 1;
    }
}

$kernel->define(ValidationExceptionTranslationHandler::class, fn() => new ValidationExceptionTranslationHandler())
       ->tag('exception.translator.handlers');

use Meritum\HttpExceptionHandler\ErrorEnvelope;

// From a caught domain exception
$envelope = ErrorEnvelope::fromDomainException($domainException);

// With explicit values
$envelope = new ErrorEnvelope('HTTP_403', 403, 'Forbidden', 'You do not have permission.');

return new JsonResponse($envelope, $envelope->status);

$envelope = ErrorEnvelope::fromDomainException($domainException)
    ->withErrors([
        ['field' => 'email', 'message' => 'Must be a valid email address.'],
        ['field' => 'age',   'message' => 'Must be an integer greater than 0.'],
    ]);

return new JsonResponse($envelope, $envelope->status);