PHP code example of snicco / psr7-error-handler

1. Go to this page and download the library: Download snicco/psr7-error-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/ */

    

snicco / psr7-error-handler example snippets


use Psr\Log\LogLevel;
use Snicco\Component\Psr7ErrorHandler\Information\ExceptionInformation;
use Snicco\Component\Psr7ErrorHandler\Log\RequestAwareLogger;
use Snicco\Component\Psr7ErrorHandler\Log\RequestLogContext;

$monolog = new Monolog\Logger();

$request_aware_logger = new RequestAwareLogger($monolog);

// With custom exception levels.
// By default, any status code > 500 will be LogLevel::CRITICAL
// Anything below will be LogLevel::ERROR
$request_aware_logger = new RequestAwareLogger($monolog, [
    Throwable::class => LogLevel::ALERT,
    MyCustomException::class => LogLevel::WARNING  
])

// With custom log context:
class AddIPAddressFor403Exception implements RequestLogContext {

    public function add(array $context, ExceptionInformation $information) : array{
        
        if(403 === $information->statusCode()) {
            $context['ip'] = $information->serverRequest()->getServerParams()['REMOTE_ADDR'];
        }
        return $context;
    }
}

// The last argument is variadic.
$request_aware_logger = new RequestAwareLogger($monolog, [], new AddIPAddressFor403Exception());


use Snicco\Component\Psr7ErrorHandler\Identifier\SplHashIdentifier;
use Snicco\Component\Psr7ErrorHandler\Information\InformationProviderWithTransformation;

// uses spl_object_hash to uniquely identify exceptions.
$identifier = new SplHashIdentifier();

// This will use the error messages in /resources/en_US.error.json
$information_provider = InformationProviderWithTransformation::fromDefaultData($identifier);

// Or with custom error messages
$error_messages = [
    // The 500 status code is mandatory. All other HTTP status codes are optional.
    500 => [
        'title' => 'Whoops, this did not work...',
        'message' => 'An error has occurred... We are sorry.'
    ];
]
$information_provider = new InformationProviderWithTransformation($error_messages, $identifier);

use Snicco\Component\Psr7ErrorHandler\Information\ExceptionTransformer;

class CustomAuthenticationTo404Transformer implements ExceptionTransformer {
    
    public function transform(Throwable $e) : Throwable{
        
        if(!$e instanceof MyCustomAuthenticationException) {
            return $e;
        }
        
        // Key value pairs of headers that will later be added to the PSR-7 response.
        $response_headers = [
            'WWW-Authenticate' => '/login'    
        ];
        
        // The status code that should be used for the PSR-7 response.
        $status_code = 401;
        
        return \Snicco\Component\Psr7ErrorHandler\HttpException::fromPrevious($e, $status_code, $response_headers);
    }
}

$identifier = new SplHashIdentifier();

$information_provider = InformationProviderWithTransformation::fromDefaultData(
    $identifier,
    new CustomAuthenticationTo404Transformer() // Last argument is variadic
);


use Psr\Log\LogLevel;
use Snicco\Component\Psr7ErrorHandler\DisplayerFilter\CanDisplay;
use Snicco\Component\Psr7ErrorHandler\DisplayerFilter\ContentType;
use Snicco\Component\Psr7ErrorHandler\DisplayerFilter\Delegating;
use Snicco\Component\Psr7ErrorHandler\DisplayerFilter\Verbosity;
use Snicco\Component\Psr7ErrorHandler\Identifier\SplHashIdentifier;
use Snicco\Component\Psr7ErrorHandler\Information\InformationProviderWithTransformation;
use Snicco\Component\Psr7ErrorHandler\Log\RequestAwareLogger;
use Snicco\Component\Psr7ErrorHandler\ProductionErrorHandler;

// Use any PSR-7 response factory
$psr_7_response_factory = new Nyholm\Psr7\Factory\Psr17Factory();

$request_aware_logger = new RequestAwareLogger(
    new Monolog\Logger(), // Use any PSR-3 logger
);

$information_provider = InformationProviderWithTransformation::fromDefaultData(
    new SplHashIdentifier()
);

$prefer_verbose = (bool) getenv('APP_DEBUG');

$displayer_filter = new Delegating(
    new ContentType(),
    new Verbosity($prefer_verbose),
    new CanDisplay(),
);

$error_handler = new ProductionErrorHandler(
    $psr_7_response_factory,
    $request_aware_logger,
    $information_provider,
    $displayer_filter,
    // Custom exception displayers go here (variadic)
)

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Server\MiddlewareInterface;
use Snicco\Component\Psr7ErrorHandler\HttpErrorHandler;

class ErrorHandlerMiddleware implements MiddlewareInterface {
    
    private HttpErrorHandler $error_handler;
    
    public function __construct(HttpErrorHandler $error_handler) {
        $this->error_handler = $error_handler;
    }
    
    public function process(ServerRequestInterface $request,RequestHandlerInterface $handler) : ResponseInterface{
        
        try {
            return $handler->handle($request);
        }catch (Throwable $e) {
            return $this->error_handler->handle($e, $request);
        }
    }
    
}