我可以在Silex中禁用错误/异常处理吗


Can I disable error/exception handling in Silex?

我正在构建一个基于Silex 1.3的应用程序。这是我第一次接触Silex,所以我对它不是很熟悉

我想使用我自己的错误/异常处理程序,它基本上是一个注册自己的类,然后捕获所有错误、致命错误和未捕获的异常并处理它们,无论是在开发中使用Whoops,还是在生产中使用优雅的处理程序。

然而,一旦我进入silex控制器、中间件,无论什么,silex都会接管并使用它自己的错误处理。我的仍然会遇到致命的错误,因为Silex显然没有挂断,但其他所有内容都被Silex的默认"出现问题"页面所取代。

我确实知道我可以使用$app->error()来覆盖Silex如何处理错误,但我还没有找到一种方法从那里将事情设置回原始的ErrorHandler,或者覆盖Silex是否处理错误。

那么,有人知道如何a)告诉Silex使用我的错误处理程序,使用$app->error()或其他方式,b)完全禁用Silex中的错误处理,或者c)作为最后手段,让Silex捕捉致命错误,这样我就可以处理$app->error()中的所有三种类型吗

由于这是我第一次使用Silex,如果有更好的方法,请随时纠正我或向我展示如何处理Silex中的错误,但如果可以的话,也请回答这个问题

一些示例代码:

// This will register itself and then handle all errors.
$handler = new ErrorHandler();
// These are all handled appropriately.
nonexistentfunction();            // Correctly caught by ErrorHandler::handleFatalError
trigger_error("example");         // Correctly caught by ErrorHandler::handlePhpError
throw new 'Exception("example");  // Correctly caught by ErrorHandler::handleException
$app = new 'Silex'Application();
$app->get('/', function () use ($app) {
    // This is still handled correctly.
    nonexistentfunction();            // Correctly caught by ErrorHandler::handleFatalError
    // However, these are now overridden by Silex.
    trigger_error("example");         // INCORRECTLY DISPLAYS SILEX ERROR PAGE.
    throw new 'Exception("example");  // INCORRECTLY DISPLAYS SILEX ERROR PAGE.
});
$app->run();

还有一个非常简化的ErrorHandler供参考:

Class ErrorHandler
{
    public function __construct()
    {
        $this->register();
    }
    private function register()
    {
        register_shutdown_function( array($this, "handleFatalError") );
        set_error_handler(array($this, "handlePhpError"));
        set_exception_handler(array($this, "handleException"));
    }
    // Etc.
}

我知道(b)选项,你可以完全禁用Silex应用程序错误处理程序,之后,你的自定义错误处理程序应该可以像你定义的那样正常工作。

完全禁用Silex错误处理程序:

$app['exception_handler']->disable();

所以,它会像:

require_once  'Exception.php'; # Load the class
$handler = new ErrorHandler(); # Initialize/Register it
$app = new 'Silex'Application();
$app->get('/', function () use ($app) {

    nonexistentfunction();  
    trigger_error("example");
    throw new 'Exception("example");
});
$app->run();

请注意,ExceptionHandler::disable()在1.3中已被弃用,在2.0中已被删除。因此:

在Silex 2.0之前:

$app['exception_handler']->disable();

在Silex 2.0+中:

unset($app['exception_handler']);

请参阅Silex文档

看起来,您还需要注册一个ExceptionHandler。Silex会将致命错误转化为异常来处理它们。此外,如果我没记错的话,当"抛出"到控制器和中间件内部时(至少在中间件之前),这种异常会被捕获,但在模型内部不会。

最后,您可以添加以下内容来处理问题。

// register generic error handler (this will catch all exceptions)
$app->error(function ('Exception $e, $exceptionCode) use ($app) {
    //if ($app['debug']) {
    //    return;
    //}
    return 'Service'SomeHelper::someExceptionResponse($app, $e);
});
return $app;

我希望这能有所帮助。

您必须在应用程序中注册特定的提供商:https://github.com/whoops-php/silex-1