Giter Site home page Giter Site logo

whoops's Introduction

whoops

PHP errors for cool kids

Total Downloads Latest Version Build Status on newer versions Scrutinizer Quality Score Code Coverage


Whoops!

whoops is an error handler framework for PHP. Out-of-the-box, it provides a pretty error interface that helps you debug your web projects, but at heart it's a simple yet powerful stacked error handling system.

Features

  • Flexible, stack-based error handling
  • Stand-alone library with (currently) no required dependencies
  • Simple API for dealing with exceptions, trace frames & their data
  • Includes a pretty rad error page for your webapp projects
  • Includes the ability to open referenced files directly in your editor and IDE
  • Includes handlers for different response formats (JSON, XML, SOAP)
  • Easy to extend and integrate with existing libraries
  • Clean, well-structured & tested code-base

Sponsors

Blackfire.io

Installing

If you use Laravel 4, Laravel 5.5+ or Mezzio, you already have Whoops. There are also community-provided instructions on how to integrate Whoops into Silex 1, Silex 2, Phalcon, Laravel 3, Laravel 5, CakePHP 3, CakePHP 4, Zend 2, Zend 3, Yii 1, FuelPHP, Slim, Pimple, Laminas, or any framework consuming StackPHP middlewares or PSR-7 middlewares.

If you are not using any of these frameworks, here's a very simple way to install:

  1. Use Composer to install Whoops into your project:

    composer require filp/whoops
  2. Register the pretty handler in your code:

    $whoops = new \Whoops\Run;
    $whoops->pushHandler(new \Whoops\Handler\PrettyPageHandler);
    $whoops->register();

For more options, have a look at the example files in examples/ to get a feel for how things work. Also take a look at the API Documentation and the list of available handlers below.

You may also want to override some system calls Whoops does. To do that, extend Whoops\Util\SystemFacade, override functions that you want and pass it as the argument to the Run constructor.

You may also collect the HTML generated to process it yourself:

$whoops = new \Whoops\Run;
$whoops->allowQuit(false);
$whoops->writeToOutput(false);
$whoops->pushHandler(new \Whoops\Handler\PrettyPageHandler);
$html = $whoops->handleException($e);

Available Handlers

whoops currently ships with the following built-in handlers, available in the Whoops\Handler namespace:

  • PrettyPageHandler - Shows a pretty error page when something goes pants-up
  • PlainTextHandler - Outputs plain text message for use in CLI applications
  • CallbackHandler - Wraps a closure or other callable as a handler. You do not need to use this handler explicitly, whoops will automatically wrap any closure or callable you pass to Whoops\Run::pushHandler
  • JsonResponseHandler - Captures exceptions and returns information on them as a JSON string. Can be used to, for example, play nice with AJAX requests.
  • XmlResponseHandler - Captures exceptions and returns information on them as a XML string. Can be used to, for example, play nice with AJAX requests.

You can also use pluggable handlers, such as SOAP handler.

Authors

This library was primarily developed by Filipe Dobreira, and is currently maintained by Denis Sokolov. A lot of awesome fixes and enhancements were also sent in by various contributors. Special thanks to Graham Campbell and Markus Staab for continuous participation.

whoops's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

whoops's Issues

Custom data providers

Edited after realizing that I was short-sighted

I wish to use Whoops to display exceptions from the past,
as a history display tool.
For that I need to modify notably Frame, to allow injection of custom
file contents provider instead of existing hardcoded file_get_contents,
and also PrettyPageHandler to allow injection of custom super globals.

I am ready to submit a pull request, but I want to check with you
beforehand to see if you would accept such a pull request.

Out of memory error

Hi, I'm getting an out of memory error sometimes (but not always).
PHP Version: PHP 5.3.10-1ubuntu3.6 with Suhosin-Patch (cli) (built: Mar 11 2013 14:31:48) Copyright (c) 1997-2012 The PHP Group Zend Engine v2.3.0, Copyright (c) 1998-2012 Zend Technologies with Xdebug v2.2.1, Copyright (c) 2002-2012, by Derick Rethans

Apache version: Server version: Apache/2.2.22 (Ubuntu)
Ubuntu version: Ubuntu 12.04.2 LTS

The following is from the apache error log:
[Fri Jul 05 11:46:58 2013] [error] [client 127.0.0.1] PHP Fatal error: Allowed memory size of 1073741824 bytes exhausted (tried to allocate 950988674 bytes) in /var/www/test/vendor/filp/whoops/src/Whoops/Resources/pretty-template.php on line 129, referer: http://localhost/

The referenced line contains the following:
<td><?php echo $e(print_r($value, true)) ?></td>

I think it might be choking up on recursive structure, but I don't really know if this could be considered a PHP bug instead of a bug with whoops.

Fix annotation typehint namespaces to work with PHPStorm

A lot, if not all of the namespaces in the annotation type hints do not have \'s in front of them, and this makes PHPStorm act a little weird. Not sure if other IDE's also do this, but it shouldn't be that difficult of a fix.

Also, \Whoops\Run::pushHandler()'s annotation typehint for $handler is wrong. Its currently Whoops\HandlerInterface when it should be \Whoops\Handler\HandlerInterface, or just HandlerInterface, as its already being used at the top.

error while echo'ing non-existant variable

Hi,
I was just trying whoops out on plain PHP script (no framework or anything) with just ($var was never declared).

This is what I got:

( ! ) Notice: Undefined offset: 1 in vendor/filp/whoops/src/Whoops/Exception/Inspector.php on line 72
Call Stack
#   Time    Memory  Function    Location
1   0.0000  129708  {main}( )   ../index.php:0
2   0.0000  218364  Whoops\Run->handleError( )  ../index.php:41
3   0.0000  223836  Whoops\Run->handleException( )  ../Run.php:229
4   0.0000  248920  Whoops\Handler\PrettyPageHandler->handle( ) ../Run.php:180
5   0.0000  249456  Whoops\Exception\Inspector->getFrames( )    ../PrettyPageHandler.php:77

( ! ) Fatal error: Unsupported operand types in vendor/filp/whoops/src/Whoops/Exception/Inspector.php on line 72
Call Stack
#   Time    Memory  Function    Location
1   0.0000  129708  {main}( )   ../index.php:0
2   0.0000  218364  Whoops\Run->handleError( )  ../index.php:41
3   0.0000  223836  Whoops\Run->handleException( )  ../Run.php:229
4   0.0000  248920  Whoops\Handler\PrettyPageHandler->handle( ) ../Run.php:180
5   0.0000  249456  Whoops\Exception\Inspector->getFrames( )    ../PrettyPageHandler.php:77

array (size=4)
  'type' => int 1
  'message' => string 'Unsupported operand types' (length=25)
  'file' => string '/var/www/html/whoops/vendor/filp/whoops/src/Whoops/Exception/Inspector.php' (length=74)
  'line' => int 72

and this is what (temporarily) fixed it for me (in vendor/filp/whoops/src/Whoops/Exception/Inspector.php, line 71):

+++ $frames[1] = isset($frames[1]) ? $frames[1] + $frames[0] : $frames[0];
--- $frames[1] = $frames[1] + $frames[0];

My whoops set up is as follows:

use Whoops\Handler\PrettyPageHandler;
use Whoops\Handler\JsonResponseHandler;

$run     = new Whoops\Run;
$handler = new PrettyPageHandler;

$handler->setPageTitle("whoops test");

$run->pushHandler($handler);
$run->register();

// here goes my little test
echo $var;

Just thought you'd like to know. I'm not experienced programmer, so there may be somethin I am doing wrong and it's not whoops! fault at all :)

Thanks,
Peter

Status code

Is there a way to send a status code every time whoops catches an error?

I tried it like this:

$whoops = new Whoops\Run;
$whoops->sendHttpCode(500);
$whoops->register();

Method sendHttpCode is returning 500 correctly but its not getting set in the header correctly.

Integration with eloquent/asplode

When using eloquent/asplode (converting errors to ErrorException) along with flip/whoops, the displayed details are not correct.

Particularly, it is reported that the ErrorException is triggered from vendor/filp/whoops/src/Whoops/Run.php:243 while a syntax error occurred in a different file. The correct file and line are not reported. The error message is reported as the exception message at the top.

Here is the reported codeblock for your reference:

  {
        if($error = error_get_last()) {
            $this->handleError(
                $error['type'],
                $error['message'],
                $error['file'],
                $error['line']
            );
        }
    }

Proposal: Change name?

There were some concerns with the name I've chosen for this library, particularly in an environment where it might have to be written down and shown to some higher-ups.

So this is both a question and a call for suggestions:

  1. Should the name change?
  2. Any name ideas?

[silex] Fatal error: Uncaught exception 'RuntimeException'

In my Silex app, sometimes the following gets appended to my output. It's always after the </html> tag, and usually refreshing the page makes it go away. It happens on random pages, so i'm not sure yet what might cause this.
Do you have any idea what might cause this, or should I dig deeper myself?

Sample output:

Fatal error: Uncaught exception 'RuntimeException' with message 'Accessed request service outside of request scope. Try moving that call to a before handler or controller.' in /[snip]/vendor/silex/silex/src/Silex/Application.php:133 Stack trace: 
#0 /[snip]/vendor/pimple/pimple/lib/Pimple.php(83): Silex\{closure}(Object(Bolt\Application)) 
#1 /[snip]/vendor/filp/whoops/src/Whoops/Provider/Silex/WhoopsServiceProvider.php(32): Pimple->offsetGet('request') 
#2 [internal function]: Whoops\Provider\Silex\{closure}(Object(Whoops\Exception\ErrorException), Object(Whoops\Exception\Inspector), Object(Whoops\Run)) 
#3 /[snip]/vendor/filp/whoops/src/Whoops/Handler/CallbackHandler.php(46): call_user_func(Object(Closure), Object(Whoops\Exception\ErrorException), Object(Whoops\Exception\Inspector), Object(Whoops\Run)) 
#4 /[snip]/vendor/filp/whoops/src/Whoops/Run.php(158): Whoops\Handler\CallbackHandler->handle(Object(Whoops\Excepti in /[snip]/vendor/silex/silex/src/Silex/Application.php on line 133

Line 276 on Run.php Max execution time error

No clue why this is happening, but whenever I let an exception bubble up I get a max execution time error. Any ideas why? I'm working with a project here on github. SpeedyPHP/Framework, file App.php in lib/Speedy sets up Whoops.

1.1.0 Feature/improvement list

The following are new features and improvements scheduled for the 1.1.0 release; it's a living ticket, and new goals will be added as progress is made. This single issue will serve as a general goal-tracker, mostly for personal organization. Individual issues should still be created for bugs.

New features:

  • Mobile layout support (PrettyPageHandler)
  • #15 - Trace arguments display within PrettyPageHandler
  • #43 - Implement chained exceptions display within PrettyPageHandler (already in the core)
  • Better templating system with support for custom css, js and html template blocks (PrettyPageHandler)
  • Share/export feature to easily export exception message to a copy-paste-friendly format (PrettyPageHandler)
  • Whoops JS API (PrettyPageHandler)

Improvements:

  • Remove Zend provider from the core
  • Overhauled pretty-template.php, right now it's a mess and will quickly grow impossible to maintain (PrettyPageHandler)

Integration with Xdebug to improve error handler

It seems whoops is focusing more on exception handling than error handling. I am currently using Xdebug and the HTML stacktraces. http://xdebug.org/docs/stack_trace I'm wondering if the whoops error handler could be improved by integrating with Xdebug.

For example, using this example code:

<?php
require __DIR__ . '/vendor/autoload.php';

$run = new Whoops\Run;
$handler = new Whoops\Handler\PrettyPageHandler;
$run->pushHandler($handler);
$run->register();

bar();

Whoops doesn't show me the line number where the error occurred or a stacktrace. If I use xdebug's error messages I do get line numbers and a stacktrace.

Edit: After looking into it, you can get the backtrace without using Xdebug. I made some progress by adding this code to getFrames() in Inspector.php

if ($this->exception instanceof ErrorException) {
    $frames = debug_backtrace();
}

Stack trace on syntax error

When a syntax error occurs, an ErrorException is generated from the shutdown handler. This appears to create an invalid stack trace, as you can see in the image below. Am I doing something wrong or should this issue be addressed?

To circumvent this issue in my application I've temporarily added the option to let ErrorException generate a custom stack trace from its getLine() and getFile() methods.

image

New ob_end_clean code in PrettyPageHandler causing problems

Since the PrettyPageHandler now uses ob_end_clean, it is impossible to capture the exception output as a string. I need to be able to get the exception output as a raw string rather than having the handler echo it out directly. This allows me to return a 500 level response from Laravel.

Any suggestions or changes that can be made?

REPL

I don't know if this is even possible in php but for ruby there exists a Gem (https://github.com/charliesome/better_errors) providing support for a REPL inside the browser for debugging and runtime information. I never saw something like this in PHP but I think that might be great and a huge improvement to the PHP community.

What do you guys think about this feature request?

Issue #71 requires reopening

#71 has been merged in and closed, and then it seems the history has been rewritten, because the merge is not in anymore.

If that was intentional, just let me know. If this was a mistake, you might want to merge again.

Display exception error code in PrettyPageHandler

We use HTTP Status Codes as exception error codes in our API controllers (40x). When such an exception is thrown, and intentionally not caught in development, it would be nice to see the error code somewhere in the PrettyPageHandler!

eval

If an error occurs in eval'd code, this error then Whoops/Exception/Frame:: getFileContents throws an error and you cannot view the actual error that occurred.

Document API

In preparation for the 1.0.0 release, at least the following components must be documented outside code comments:

  • Whoops\Run
  • PrettyPageHandler
  • JsonResponseHandler

Codeigniter Integration

I have always found CodeIgniters error reporting a little lack luster, and became a huge fan of Whoops when I was using Laravel 4 for a hackathon recently.

Any possibility or ideas on how one would integrate this with say CodeIgniter?

Detect console usage / do not output HTML on console

Our Laravel 4 project uses Whoops, but whenever there's an error in one of the CLI scripts we get a massive bunch of unusable HTML code back. It would be nice if Whoops would be able to detect console usage and either not show anything and/or let the core take care of it.

Integrating logging

What would be the best way to integrate error logging with whoops? Does whoops catch errors and convert them to exceptions or any other magic that would effect logging errors/exceptions?

UTF-8 Problem

Hello!

I'm using whoops (pretty cool!) in laravel 4, and i got a problem when the database connection is rejected by the server.

The error message is generated by the server and it is in Portuguese, so I don't know to handle the utf8 problem.

[error] => Array
        (
            [type] => ErrorException
            [message] => json_encode(): Invalid UTF-8 sequence in argument
            [file] => vendor\filp\whoops\src\Whoops\Handler\JsonResponseHandler.php
            [line] => 105
        )
[error] => Array
        (
            [type] => PDOException
            [message] => SQLSTATE[HY000] [2002] Nenhuma conexão pôde ser feita porque a máquina de destino as recusou ativamente.

            [file] => vendor\laravel\frameworksrc\Illuminate\Database\Connectors\Connector.php
            [line] => 47
        )

Can we just add a utf8_encode to the exception message?

 $response = array(
            'error' => array(
                'type'    => get_class($exception),
                'message' => utf8_encode($exception->getMessage()),
                'file'    => $exception->getFile(),
                'line'    => $exception->getLine()
            )
        );

Add option to not quit after completing all handlers

If you are using a framework that has it's own Exception and error handling services, Whoops! completely takes over and does not allow the framework to use its own implementations.

For example, if I am using my choice of framework's Exception handler, but want to use \Whoops\Handler\JsonResponseHandler for AJAX requests with $json_handler->onlyForAjaxRequests(true); the PHP script will exit after iterating through the handler stack and never reach the Exception handler of the framework.

Line numbers displayed incorrectly

I get an exception, and it's displayed on line number 221 but the actual code is on line 222 in my file. So I guess you have a bug when calculating line numbers.

HTTP Status Code hijacked

Responses have 200 as HTTP Status Code, what isn't good for APIs indicating an error. So the original status code should be kept.

I don't know if this just applies for Laravel, if so, i gonna fix this.

Better integration with Zend

Hi, there is better way to intergrate Woops in Zend than coping Module.php.

In application.config.php in section module_listener_options->module_paths you can provide direct path to Whoops\Module.php

return array(
    'modules' => array(
        'Whoops',
        'Application'
    ),
    'module_listener_options' => array(
        'module_paths' => array(
            './module',
            'Whoops' => './vendor/filp/whoops/src/Whoops/Provider/Zend',
        ),
    ),
);

But even better would be to add in composer.json classmap and then only thing that you need to add to you ZF2 application is to provide module name Whoops in configuration

{
    "autoload": {
        "psr-0": {
            "WidRestApiDocumentator": "src"
        },
        "classmap": [
            "src/Whoops/Provider/Zend/Module.php"
        ]
    }
}

Autoload failing on strict errors (PHP bug 42098 workaround)

PHP bug 42098 prevents autoloading Whoops classes on strict warnings.

As a result, instead of seeing a strict warning, a user of Whoops library sees Class \Whoops\Exception\ErrorException does not exist without any traceback, because it is a fatal error.

Given that PHP devs, as usual, have marked the bug as "Not a bug", I suggest to add a tiny workaround to Whoops to pre-autoload required classes to handle a strict warning:

class_exists('\\Whoops\\Exception\\ErrorException');
class_exists('\\Whoops\\Exception\\FrameCollection');
class_exists('\\Whoops\\Exception\\Frame');
class_exists('\\Whoops\\Exception\\Inspector');

Incorrect annotations

Some of the annotation are incorrectly namespaced, and can't be interpreted by e.g. PhpStorm, where long lists of warnings are generated while running inspections.

https://github.com/filp/whoops/blob/master/src/Whoops/Run.php#L31

/**
 * Pushes a handler to the end of the stack.
 * @param  Whoops\HandlerInterface $handler
 * @return Whoops\Run
 */

Should read:

/**
 * Pushes a handler to the end of the stack.
 * @param  \Whoops\HandlerInterface $handler
 * @return \Whoops\Run
 */

Or add a use clause for Whoops\Run and you can cut it down to:

/**
 * Pushes a handler to the end of the stack.
 * @param  HandlerInterface $handler
 * @return Run
 */

Zip File Is Broken

The zip file with https://api.github.com/repos/filp/whoops/zipball/1.0.6 had unexpected end of archive. It will cause laravel4 composer install throw exception as follow:

[UnexpectedUvalueException]
C:\wamp\www\laravel\vendor/filp/whoops/f926eafa0cb6f6d5bf84706826841aa4.6
is not a zip archive.

※ I had try to clean composer cache directory C:\Users\<user>\AppData\Local\Composer and C:\Users\<user>\AppData\Roaming\Composer before install.

xdebug editor link should not require extension enabled

Currently xdebug editor link format is conditional on extension_loaded('xdebug'), however extension being enabled or disabled is in no way connected to xdebug.file_link_format being or not being set in configuration.

I routinely have extension disabled (it can be sluggish), however link format remains perfectly readable and valid configuration information, that doesn't rely on extension in any way.

Problem with ob_start()

I'm having an error in a output buffer and Whoops is using a output buffer for the output.
So PHP trows an error: ob_start(): Cannot use output buffering in output buffering display handlers in /home/dir/web/core/vendor/Whoops/Run.php on line 172
And the original output buffer breaks because of this.
So I've found a way to fix this by adding

if(!ob_get_status())  { }

around ob_start() and ob_get_clean() to check if there is all ready a output buffer running.

Thanks in regards.

Btw. Whoops is awesome :).

Remove $this->isRegistered in handleShutdown() function?

I'm currently overriding the handlers to add ob_clean(); to prevent previous output from displaying. This works great for handleException and HandleError but handleShutdown has a check for $this->isRegistered which is preventing me from using it unless I call register first.

Should the $this->isRegistered check be removed from handleShutdown? Maybe there is there a reason for it being there which I don't understand?

sendHttpCode (#75) causes PHP dev server to hang

When running whoops through the PHP dev server, sendHttpCode will cause the server to hang indefinitely. I've tracked this down to the blank header being sent in Run.php:273: header(" ", true, $this->sendHttpCode()).

Has anyone else experienced this issue?

Don't use CDNs

This is just an suggestion. Can you please use actual files instead getting them from cloudflare cdn, i am talking about js files. The reason why is that i cannot use this on the computer where i don't have internet connection. I know that today that is rare but it happens. Today i was developing laravel4 application witch include this package and i couldn't use this tool.

Thanks.

Add more editor identifiers

Currently, there are only identifiers for sublime, textmate, emacs, and macvim. Would be really nice to have more for editors like PHPStorm, Eclipse, and Netbeans

Prefix CSS classes to avoid conflicts

What about prefix all CSS classes with something like " whoops-* " ?

This can avoid conflicts and display problems with users that use some CSS framework like Bootstrap ( that already use .container class )

Handle::LAST_HANDLE and Handle::QUIT do the same thing.

Whilst looking into issue #49 (which failed because I didn't bother researching how the set_exception_handler() function works), I realised that Handle::LAST_HANDLE and Handle::QUIT do the same thing.

In the comments towards the end of Whoops\Run::handleException, it says "Check if we got here because of Handler::QUIT and if so, try to quit execution", however script execution is also terminated when $handlerResponse is equal to Handle::LAST_HANDLE.

It looks like this functionality just hasn't been written yet, so I thought I'd make an issue before making a pull request. My suggestion is to add another option, such as $quitOnFinish, but let me know what you think.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.