Error handler with PSR-7 support

Overview

Jasny Error Handler

Build Status Scrutinizer Code Quality Code Coverage SensioLabsInsight Packagist Stable Version Packagist License

Error handler with PSR-7 support.

Installation

The Jasny Error Handler package is available on packagist. Install it using composer:

composer require jasny/error-handler

Usage

$errorHandler = new Jasny\ErrorHandler();

Just creating an error handler will do nothing. You can use it for logging, handling fatal errors and as PSR-7 compatible middleware.

Logging

By default the error handler with only catch Throwables and not set the php error handler.

To log errors, set the logger using setLogger(). You can log with any PSR-3 compatible logger like Monolog.

The logUncaught() method will set the error handler, so warnings and notices can be logged. It may also register a shutdown function to handle uncatchable fatal errors.

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

$errorHandler = new Jasny\ErrorHandler();

$log = new Logger('test');
$log->pushHandler(new StreamHandler('path/to/your.log'));

// Log fatal errors, warnings and uncaught exceptions
$errorHandler->setLogger($log);

$errorHandler->logUncaught(E_PARSE | E_ERROR | E_WARNING | E_USER_WARNING);
$errorHandler->logUncaught(Exception::class);
$errorHandler->logUncaught(Error::class); // PHP7 only

PSR-7 compatible middleware

The error handler can be used as PSR-7 compatible (double-pass) middleware.

The error will catch Exceptions and Errors.

You can use this middleware with:

For example use it with Relay:

use Relay\RelayBuilder;
use Jasny\HttpMessage\ServerRequest;
use Jasny\HttpMessage\Response;

$errorHandler = new Jasny\ErrorHandler();

$relay = new RelayBuilder();
$dispatcher = $relay->newInstance([$errorHandler->asMiddleware()]);

$response = $dispatcher((new ServerRequest())->withGlobalEnvironment(), new Response());

Or with Jasny Router:

use Jasny\Router;
use Jasny\Router\Routes\Glob as Routes;
use Jasny\HttpMessage\ServerRequest;
use Jasny\HttpMessage\Response;

$router = new Router(new Routes(['/**' => ['controller' => '$1', 'id' => '$2']));

$errorHandler = new Jasny\ErrorHandler();
$router->add($errorHandler->asMiddleware());

$response = $dispatcher((new ServerRequest())->withGlobalEnvironment(), new Response());

PHP 5 support

With PHP 5 errors aren't thrown, so the middleware won't handle it. To add middleware support for errors in PHP5, you should call converErrorsToExceptions(). This method will convert an error to an ErrorException.

Handling fatal errors

Errors that are not thrown, like syntax errors, are not caught and will cause a fatal error. With the logUncaught() method, you can specify that the error handler should also these kind of errors.

With the onFatalError() method you take additional action, like output a pretty error message.

ob_start();

$errorHandler = new Jasny\ErrorHandler();

$errorHandler->logUncaught(E_ERROR | E_RECOVERABLE_ERROR | E_USER_ERROR);

$errorHandler->onFatalError(function() {
    http_response_code(500);
    header('Content-Type: text/html');
    echo "<h1>An unexpected error occured</h1><p>The error has been logged.</p>";
}, true);

Use true as second argument of onFatalError to the output buffer before calling your function.

Combine with other error handlers

Using the error logger might lose backtrace information that other error handlers can pick up. Jasny Error Handler will always call the previous error handler, including the PHP internal error handler for non-thrown errors.

When using Rollbar you should not use the Rollbar handler for Monolog. By using Rollbar's own error handler, you'll get better error reports:

use Jasny\ErrorHandler;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// Rollbar error handler will log uncaught errors
Rollbar::init(array('access_token' => 'POST_SERVER_ITEM_ACCESS_TOKEN'));

$log = new Logger('test');
$log->pushHandler(new RollbarHandler(Rollbar::$instance));

$errorHandler = new ErrorHandler();

// Jasny error handler will only log caught errors
$errorHandler->setLogger($log);
You might also like...
think-exception-handler
think-exception-handler

ThinkPHP6.0 exception 异常插件 安装 composer require tinywan/think-exception 配置 发布配置 php think tinywan:exception 这将自动生成 config/exception.php 配置文件。 配置异常类 a

Analyzes PHPStan baseline files and creates aggregated error trend-reports

Analyzes phpstan baseline files Analyzes PHPStan baseline files and creates aggregated error trend-reports.

This script allows to bypass Oracle Cloud Infrastructure 'Out of host capacity' error immediately when additional OCI capacity will appear in your Home Region / Availability domain.
This script allows to bypass Oracle Cloud Infrastructure 'Out of host capacity' error immediately when additional OCI capacity will appear in your Home Region / Availability domain.

Resolving Oracle Cloud "Out of Capacity" issue and getting free VPS with 4 ARM cores / 24GB of memory Very neat and useful configuration was recently

Hi everyone! This is our repository for our final project in college. We're sorry if so many bug or error. Thank You

About The Project Hi everyone! This is our repository for our final project in college. We're sorry if so many bug or error. Thank You About Laravel L

Better error reporting for PHP, and prettier too!
Better error reporting for PHP, and prettier too!

PHP Error | Improve Error Reporting for PHP THIS IS NO LOBGER MAINTAINED, Please leave me alone. PHP errors are not good enough for development, it's

The tool converts different error reporting standards for deep compatibility with popular CI systems (TeamCity, IntelliJ IDEA, GitHub Actions, etc).
The tool converts different error reporting standards for deep compatibility with popular CI systems (TeamCity, IntelliJ IDEA, GitHub Actions, etc).

JBZoo / CI-Report-Converter Why? Installing Using as GitHub Action Example GitHub Action workflow Available Directions Help description in terminal Co

Provides the ability to notify developers of error logs via email or SMS.

🔔 Dev Notify Plugin 🚨 Requires OctoberCMS 2.0 ✨ What does this plugin do? Provides the ability to notify developers of error logs via email or SMS.

This Validate Class is for those who are looking for a validator that returns a code for every each error (Laravel/Api)
This Validate Class is for those who are looking for a validator that returns a code for every each error (Laravel/Api)

Validator-Class This Validate Class is for those who are looking for a validator that returns a code for every each error (Laravel/Api) Requirements A

Comments
  • Scrutinizer Auto-Fixes

    Scrutinizer Auto-Fixes

    @jasny requested this pull request.

    It consists of patches automatically generated for this project on Scrutinizer: https://scrutinizer-ci.com/g/jasny/error-handler/

    opened by scrutinizer-auto-fixer 0
  • How to catch this error?

    How to catch this error?

    $errorHandler = new Jasny\ErrorHandler();
    
    $logger = new \Monolog\Logger("test");
    $logger->pushHandler(new \Monolog\Handler\StreamHandler(__DIR__."/test.log"));
    
    $errorHandler->setLogger($logger);
    
    $errorHandler->logUncaught(E_PARSE | E_ERROR | E_WARNING | E_USER_WARNING);
    $errorHandler->logUncaught(Exception::class);
    $errorHandler->logUncaught(Error::class); // PHP7 only
    
    echo "{$x}";
    echo $x;
    

    That is my code, but when i run it, the error-handler can not catch the error and log it into the log file.

    opened by KomaBeyond 0
  • Test each trait individually

    Test each trait individually

    Currently there is a single unit test for ErrorHandler that also covers all traits. Instead we should split up the test so each trait has it's own testcase.

    opened by jasny 0
Releases(v0.2.0)
Owner
Arnold Daniels
Web and blockchain developer at @ltonetwork
Arnold Daniels
A small, modern, PSR-7 compatible PSR-17 and PSR-18 network library for PHP, inspired by Go's net package.

Net A small, modern, PSR-7 compatible PSR-17 and PSR-18 network library for PHP, inspired by Go's net package. Features: No hard dependencies; Favours

Minibase 16 Jun 7, 2022
A small, modern, PSR-7 compatible PSR-17 and PSR-18 network library for PHP, inspired by Go's net package.

Net A small, modern, PSR-7 compatible PSR-17 and PSR-18 network library for PHP, inspired by Go's net package. Features: No hard dependencies; Favours

Minibase 16 Jun 7, 2022
Testing utilities for the psr/log package that backs the PSR-3 specification.

FIG - Log Test Testing utilities for the psr/log package that backs the PSR-3 specification. Psr\Log\Test\LoggerInterfaceTest provides a base test cla

PHP-FIG 3 Nov 19, 2022
A simple implementation of the api-problem specification. Includes PSR-15 support.

ApiProblem This library provides a simple and straightforward implementation of the IETF Problem Details for HTTP APIs, RFC 7807. RFC 7807 is a simple

Larry Garfield 236 Dec 21, 2022
An alternative Redis session handler for PHP featuring per-session locking and session fixation protection

RedisSessionHandler An alternative Redis session handler featuring session locking and session fixation protection. News phpredis v4.1.0 (released on

Marcel Hernandez 117 Oct 19, 2022
AWS DynamoDB session handler for Magento (experimental!)

Magento Session Handler for AWS DynamoDB Author: Fabrizio Branca TODO: disable automatic gc create cron that does gc how does it keep track of lifetim

AOE 5 Apr 6, 2017
Redis-based session handler for Magento with optimistic locking

Cm_RedisSession A Redis-based session handler for Magento with optimistic locking. Features: Falls back to mysql handler if it can't connect to Redis.

Colin Mollenhour 216 Jan 5, 2023
A Redis-based session handler for Magento with optimistic locking.

Cm_RedisSession A Redis-based session handler for Magento with optimistic locking. Features: Falls back to mysql handler if it can't connect to Redis.

Colin Mollenhour 215 Jan 28, 2022
A Redis-backed PHP session handler with optimistic locking

php-redis-session-abstract A Redis-based session handler with optimistic locking. Features: When a session's data size exceeds the compression thresho

Colin Mollenhour 59 Dec 16, 2022
Personal PHP MySQL query handler based on Eloquent using PDO.

?? Equivoluent Welcome to "Equivoluent" my personal PHP MySQL query handler using PDO. Equivoluent is based on Laravel's Eloquent. The goal of "Equivo

Wob Jelsma 2 Sep 7, 2022