gpt4 book ai didi

php - 如何在 Symfony2/Silex 中捕获错误和异常?

转载 作者:行者123 更新时间:2023-12-03 21:35:38 30 4
gpt4 key购买 nike

我想在我的 Silex 应用程序中捕获错误和异常,以将它们包装在将始终返回给客户的自定义 JSON 响应中。我发现了三种基本方法:

$app->error()
Symfony\Component\Debug\ErrorHandler::register();
Symfony\Component\Debug\ExceptionHandler::register();

虽然我能够使用 error() 捕获 Controller 异常,但我因 php 错误而失败 - 它们总是以 xdebug 结束。我也不明白 error()ExceptionHandler::register() 是如何相互作用的——我需要两者吗?如何确保我的 error() 响应是 JSON?

我现在有以下示例代码:

use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class Router extends Silex\Application
{
function __construct() {
parent::__construct();

// routes
$this->match('/{context}', array($this, 'handler'));

// error handler
$this->error(function(\Exception $e, $code) {
return $this->json(array("error" => $e->getMessage()), $code);
});
}

function handler(Request $request, $context) {
// throw new \Exception('test'); // exception- this is caught
$t = new Test(); // error- this is not caught

return 'DONE';
}
}

Symfony\Component\Debug\ErrorHandler::register();

$app = new Router();
$app->run();

最佳答案

ErrorHandler::register();你可以像异常一样捕获你的错误

例子

use Symfony\Component\Debug\ExceptionHandler;
use Symfony\Component\Debug\ErrorHandler;

///bla bla bla some code

//catch all errors and convert them to exceptions
ErrorHandler::register();

try {
//for example error happens here
trigger_error( 'OH MY GOD, I AM ON FIRE' );
} catch ( \Exception $e ) {

//for debugging you can do like this
$handler = new ExceptionHandler();
$handler->handle( $e );

/*
* ExceptionHendler class comments
* It is mostly useful in debug mode to replace the default PHP/XDebug
* output with something prettier and more useful.
* so i suggest to create json response
* and replace this code $handler = new ExceptionHandler();
* $handler->handle( $e );
*/
return new JsonResponse(
array(
'status' => 'error',
'message' => $e->getMessage()
)
);
}

有了 silex,你可以做下一步

ErrorHandler::register();
//register an error handler
$app->error(function ( \Exception $e, $code ) use ($app) {

//return your json response here
$error = array( 'message' => $e->getMessage() );

return $app->json( $error, 200 );
});

关于php - 如何在 Symfony2/Silex 中捕获错误和异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28089916/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com