gpt4 book ai didi

exception - Silex:特定异常类型的错误处理程序

转载 作者:行者123 更新时间:2023-12-03 07:04:58 26 4
gpt4 key购买 nike

Silex 中是否可以根据抛出的异常使用错误处理程序?

我知道这可以通过单个异常处理程序和抛出异常的类名上的 switch 语句来实现,但对我来说,“Silex 方式”似乎更干净,但不起作用。

这就是我期望的工作方式

<?php
// Handle access denied errors
$app->error(function (\App\Rest\Exception\AccessDenied $e) {
$message = $e->getMessage() ?: 'Access denied!';
return new Response($message, 403);
});
// Handle Resource not found errors
$app->error(function (\App\Rest\Exception\ResourceNotFound $e) {
$message = $e->getMessage() ?: 'Resource not found!';
return new Response($message, 404);
});
// Handle other exception as 500 errors
$app->error(function (\Exception $e, $code) {
return new Response($e->getMessage(), $code);
});

问题是,当我在 Controller 中抛出 ResourceNotFound 异常时,会执行与 AccessDenied 相关的错误处理程序

Catchable fatal error: Argument 1 passed to {closure}() must be an instance of App\Rest\Exception\AccessDenied, instance of App\Rest\Exception\ResourceNotFound given

这可以通过其他方式实现吗?或者我应该将所有内容填充到与通用异常一起使用的处理程序中,并打开抛出的异常类型?

PS:我知道 $app->abort() 方法,但更喜欢处理异常

最佳答案

编辑:此功能现已纳入 Silex 核心!

<小时/>

目前这是不可能的。现在,您必须要么拥有一个带有 switch 语句的处理程序,要么拥有多个带有 if ($e instanceof MyException) 的处理程序。

不过我确实喜欢这个想法,并且应该可以通过使用反射来实现它。如果您可以创建一张新票证,那就太好了 on the tracker ,或者如果您有兴趣,甚至可以开发补丁。

干杯!

关于exception - Silex:特定异常类型的错误处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9841414/

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