我想在我的图书馆里抓到一个拉拉维尔异常。
namespace Marsvin\Output\JoomlaZoo;
class Compiler
{
protected function compileItem($itemId, $item)
{
$boom = explode('_', $itemId);
$boom[0][0] = strtoupper($boom[0][0]);
$className = __NAMESPACE__."\\Compiler\\".$boom[0];
try {
$class = new $className(); // <-- This is line 38
} catch(\Symfony\Component\Debug\Exception\FatalErrorException $e) {
throw new \Exception('I\'m not being thrown!');
}
}
}
这是我得到的例外:
file: "C:\MAMP\htdocs\name\app\libraries\WebName\Output\JoomlaZoo\Compiler.php"
line: 38
message: "Class 'Marsvin\Output\JoomlaZoo\Compiler\Deas' not found"
type: "Symfony\Component\Debug\Exception\FatalErrorException"
这个班的名字是故意弄错的。
编辑1:
我注意到,如果在try
语句中抛出异常,就可以捕获异常:
try {
throw new \Exception('I\'d like to be thrown!');
} catch(\Exception $e) {
throw new \Exception('I\'m overriding the previous exception!'); // This is being thrown
}
发布于 2014-10-30 01:48:57
问题是您试图在类中捕获一个FatalErrorException
,但是Laravel不会让一个致命的错误返回到那里;它会立即终止。如果您试图捕获另一种异常,您的代码就会正常工作。
您可以在 method中捕获和处理app/start/global.php
中的致命错误,但这无助于处理库中的异常,也无助于以任何特定的方式处理异常。一个更好的选择是触发一个“可捕捉的”异常(例如来自Illuminate
的东西),或者根据您要检查的条件抛出一个自定义异常。
在您的例子中,如果您的目标是处理未定义的类,下面是我的建议:
try {
$className = 'BadClass';
if (!class_exists($className)) {
throw new \Exception('The class '.$className.' does not exist.');
}
// everything was A-OK...
$class = new $className();
} catch( Exception $e) {
// handle the error, and/or throw different exception
throw new \Exception($e->getMessage());
}
https://stackoverflow.com/questions/26635460
复制相似问题