[英]Slim 4 catching php warnings, notices & errors
I just started using the slim framework and want to catch php warnings, notices and errors with a custom error handler.我刚刚开始使用 slim 框架,并希望使用自定义错误处理程序捕获 php 警告、通知和错误。
ErrorHandlerMiddleware.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
<?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();
The custom error handler is working (php warnings are not shown anymore).自定义错误处理程序正在工作(不再显示 php 警告)。 But I want to add some custom variable to the output modified by the error handler.但我想向错误处理程序修改的输出添加一些自定义变量。 This should be done by这应该由
$request = $request->withAttribute('error', $this->errtext);
$request->getAttribute('error');
but the error attribute is null.但错误属性为空。
Edit: When you define a callback function, then $this
in not in the same scope.编辑:当您定义回调函数时, $this
不在同一范围内。 Also the middleware instance itself will not be "resumed" when an error occurs.当发生错误时,中间件实例本身也不会“恢复”。 Another approach would be to throw a custom Exception to catch and render it within another middleware.另一种方法是抛出自定义异常以在另一个中间件中捕获并呈现它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.