Slim 4 捕获 php 警告、通知和错误

Slim 4 catching php warnings, notices & errors

我刚开始使用 slim 框架,想用自定义错误处理程序捕获 php 警告、通知和错误。

ErrorHandlerMiddleware.php

<?php

namespace App\Middleware;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

final class ErrorHandlerMiddleware implements MiddlewareInterface {

    var $errtext;

    public function __construct() {}

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface {
        
        $errorTypes = E_ALL;
        set_error_handler(function ($errno, $errstr, $errfile, $errline) {

            $this->errtext = $errno;
            switch ($errno) {
                
                case E_USER_ERROR:
                    
                    //do something
                    break;

                case E_USER_WARNING:
                    
                    //do something
                    break;

                default:

                    //do something
                    break;

            }
            return true;

        }, $errorTypes );
        
        $request = $request->withAttribute('error',  $this->errtext);
        return $handler->handle($request);

    }
}

index.php

<?php 

    use Psr\Http\Message\ResponseInterface as Response;
    use Psr\Http\Message\ServerRequestInterface as Request;
    use Slim\Factory\AppFactory;
    use App\Middleware\ErrorHandlerMiddleware;
    
    require_once("vendor/autoload.php");

    $app = AppFactory::create();
    $app->setBasePath("/data");
    $app->addRoutingMiddleware();
    
    $app->get('/', function (Request $request, Response $response) {
        $response->getBody()->write('<a href="hello/world">Try /hello/world</a>');
        return $response;
    });

    $app->add(ErrorHandlerMiddleware::class);
    $errorMiddleware = $app->addErrorMiddleware(true, true, true);
    $app->run();

自定义错误处理程序正在运行(php 警告不再显示)。但我想向错误处理程序修改的输出添加一些自定义变量。这应该由

完成
$request = $request->withAttribute('error',  $this->errtext);
$request->getAttribute('error'); 

但错误属性为空。

编辑:定义回调函数时,$this 不在同一范围内。当发生错误时,中间件实例本身也不会被“恢复”。另一种方法是抛出自定义异常以在另一个中间件中捕获并呈现它。