Giter Site home page Giter Site logo

php-slim-whoops's Introduction

Slim whoops

PHP whoops error on slim framework

Status

Build Status Coverage Status Downloads this Month Latest Stable Version

Installation

Install the composer

curl -sS https://getcomposer.org/installer | php

Edit composer.json

Slim Whoops Version Global Mode PHP DI
1 n/a 0.1.* no no
2 1.* 0.3.* no no
3 <= 1.* 0.4.* no no
3 >= 2.* 0.5.* no no
3 >= 2.* 0.6.* yes yes
4 >= 2.* 0.7.* no no

For Slim framework 4, The composer.json will looks like

{
    "require": {
        "zeuxisoo/slim-whoops": "0.7.*"
    }
}

Now, install or update the dependencies

php composer.phar install

Basic Usage

Add to middleware with default settings

$app->add(new Zeuxisoo\Whoops\Slim\WhoopsMiddleware());

Or you can pass more settings to the WhoopsMiddleware

$app->add(new Zeuxisoo\Whoops\Slim\WhoopsMiddleware([
    'enable' => true,
    'editor' => 'sublime',
    'title'  => 'Custom whoops page title',
]));

Custom Editor String

If your editor do not included in default editor list, you can custom it like

$app->add(new Zeuxisoo\Whoops\Slim\WhoopsMiddleware([
    'editor' => function($file, $line) {
        return "http://localhost:8091?message=%file:%line";
    }
]));

Custom Handler Usage

In this usage, you can make your own handler for whoops, like:

$simplyErrorHandler = function($exception, $inspector, $run) {
    $message = $exception->getMessage();
    $title   = $inspector->getExceptionName();

    echo "{$title} -> {$message}";
    exit;
};

And then pass it to the WhoopsMiddleware:

new Zeuxisoo\Whoops\Slim\WhoopsMiddleware([], [$simplyErrorHandler]);

Important Note

Version 0.3.0 or above version

Version 0.2.0

  • You must to install the whoops library manually.

php-slim-whoops's People

Contributors

adamaveray avatar ceejayoz avatar michaelboke avatar spazzmarticus avatar vkbansal avatar zeuxisoo avatar

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

php-slim-whoops's Issues

[Request] Ability to add the resolver

the setting for editor pretty much only lets you set the editor like "phpstorm" etc. but it doesnt include the option to add the "resolver" part

 $prettyPageHandler->setEditor($this->settings['editor']);

as in

$prettyPageHandler->addEditor( 'phpstorm', 'http://localhost:8091?message=%file:%line' );

on windows we dont have a native protocol for phpstorm, so using a plugin "remote call" we can trigger the same thing using the above resolver.

https://plugins.jetbrains.com/plugin/6027-remote-call

php-slim-whoops ignores middlewares added before

Using the "better DI" way. Keep in mind that in Slim, middlewares are executed the reverse order they're added. Therefore,

In this case, You can place this line anywhere no position required

is not really true in the current state, as the middlewares added before Whoops are not executed. This may result in unintended consequences.

<?php

require('vendor/autoload.php');

$app = new \Slim\App();

$app->add(function ($req, $res, $next) {
	die('Should display this');
});

$app->add(new \Zeuxisoo\Whoops\Provider\Slim\WhoopsMiddleware($app));

$app->get('/', function ($req, $res) {
	die('Should not display this');
});

$app->run();

Add slim to required dependencies

I think is better to add slim in the required dependencies.
I've slim 3. When i require this package i get the latest version for slim 4 instead of the slim 3 compatible version.
Thanks.

For a what you disable debug mode?

...

class WhoopsMiddleware extends Middleware {
    public function call() {
        $app = $this->app;

        if ($app->config('debug') === true) {
            // Switch to custom error handler by disable debug
            $app->config('debug', false);
//          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

...

Why you make this? Debug mode is important for other components!

How to add middleware to phpErrorHandler?

I know, when placing the Middleware call into my src/middleware.php file, it will automatically replace Slim's error message with Whoops (haven't tested yet). But sometimes, I run into trouble with PHP errors.

Is there a way to replace them with Whoops too? If so, how? Haven't found it anywhere.

EDIT: Tried the rest, to see if the Error Handler is replaced, but it's not. Doing it like so: $app->response()->status(500);

This is my public/index.php file:

<?php

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

session_start();

// Instantiate the app
$settings = require __DIR__ . '/../src/settings.php';
$app = new \Slim\App($settings);

// Set up dependencies
require __DIR__ . '/../src/dependencies.php';

// Register middleware
require __DIR__ . '/../src/middleware.php';

// Register routes
require __DIR__ . '/../src/routes.php';

// Run app
$app->run();

In the src/middleware.php is the Middleware call as in the Readme $app->add(new \Zeuxisoo\Whoops\Provider\Slim\WhoopsMiddleware($app));.

Can you please create a tag for this repo

Please add a tag to your repo so that I can add to my composer.json rather than using dev-master, because if you were to make a breaking change to master, my code would break.

Call to a member function getName() on a non-object

Getting a Whoops\Exception\ErrorException as the title goes.

File and line number:
vendor/zeuxisoo/slim-whoops/src/Zeuxisoo/Whoops/Provider/Slim/WhoopsMiddleware.php:31

Here is the actual line:

'Route Name' => $app->router()->getCurrentRoute()->getName() ?: '<none>',

This only happens when I go to an URL that matches no route.

Cannot get Whoops to be default error handler.

I must be doing something lame here that is not allowing me to use Whoops to handle errors...

<?php

/** 
 * Create Slim instance
 */

$app = new \Slim\App([
    'debug' => true,
]);

/**
 * Add Whoops middleware into slim application
 */
$app->add(new \Zeuxisoo\Whoops\Provider\Slim\WhoopsMiddleware);

/** 
 * Loads environment variables from .env to getenv(), $_ENV and $_SERVER automagically.
 * Access via $app->environment[]
 */

$dotenv = new Dotenv\Dotenv('../');
$dotenv->load();

/** 
 * Require specific ENV vars to be defined.
 */
$dotenv->required(['debug']);

/** 
 * Register classes in DI Container
 */

$container = $app->getContainer();
$container->register(new \App\Services\PageService('../content/pages'));
$container->register(new \App\Services\GlobalService('../content', 'globals.yml'));
$container->register(new \Slim\Views\Twig('../templates', [
    'debug' => $app->environment['debug'],
    'cache' => '../cache/templates'
]));

/**
 * Get classes and inject into controllers as dependencies
 */
$container['App\Controllers\PageController'] = function ($c) {
    return new App\Controllers\PageController($c['page'], $c['view']);
};

/**
 * Add Twig view extensions
 */

$twig = $container->get('view')->getEnvironment();

// Twig core
$twig->addExtension(new Twig_Extension_Debug());

// Twig extensions
$twig->addExtension(new Twig_Extensions_Extension_Text());
$twig->addExtension(new Twig_Extensions_Extension_Date());

// Third party
$twig->addExtension(new Aptoma\Twig\Extension\MarkdownExtension(new Aptoma\Twig\Extension\MarkdownEngine\MichelfMarkdownEngine()));

// API
$twig->addExtension(new App\Extensions\RequestExtension($app->request));
$twig->addExtension(new App\Extensions\PageExtension($container->get('page')));
$twig->addExtension(new App\Extensions\GlobalExtension($container->get('global')));

// Helpers
$twig->addExtension(new App\Extensions\StringExtension());

/**
 * Routes
 */

include('routes.php');

/** 
 * Run app
 */

$app->run();

Any ideas why the default error pages (basic Slim error page handler is showing)?

CORS headers not set

Hey, I switched to using this middleware (and whooops) also for APIs. Endpoints accessed by javascript that encounter an exception get a 500 error message - see discussion in filp/whoops#666 ... I'd basically need to extend the PrettyPageHandler ... I guess that

  • adding support for a variable PrettyPageHandler
  • adding the ability to pass custom headers via a config option
  • or similar

might do the trick. Or do you see another way around?
Thanks

Push to packagist

Can you push the latest tag (0.2.0) up to packagist please, you can also setup packagist to automatically pull tags when you add new tags.

Also remove version from your composer.json file. This will be determined by the tag instead.

Rethrowing exceptions

On some routes, I rethrow exceptions to achieve a better user experience. When using the standard Slim 4 error middleware, the thrown ErrorException will by default generate a 500 response. When the ErrorException gets re-thrown as a HttpNotFoundException, I get a 404 error (expected behaviour). When I use php-slim-whoops, I get 500 on ErrorException (expected) but also a 500 when rethrown as HttpNotFoundException (should be 404). Am I doing something wrong or is this a bug? Example code below.

Throw an ErrorException

class Auth {
    // ...
    public function getUser($uid) { 
        if (!(v::intVal()->positive()->validate($uid))) {
            throw new ErrorException('Validation failed (positive integer required).', 550);
        }
        // ...
   }

Rethrow it

use App\Classes\Auth\Auth;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Exception\HttpBadRequestException;
use Slim\Exception\HttpNotFoundException;
use Throwable;

class Accounts extends AbstractTwigController
{
 
    public function read(Request $request, Response $response, array $args = []): Response
    {
        $auth = new Auth($this->db);
        try {
            $users = $auth->getUser($request, $args['uid']);
        } catch (Throwable $e) {
            if ($e->getCode() == 550) { 
               throw new HttpNotFoundException($request, 'User not found');
            } else {
               throw new HttpBadRequestException($request, 'Something went wrong.');
            }

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.