laravel 无法捕获 Carbon 抛出的异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31248584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:53:27  来源:igfitidea点击:

Can't catch Exception thrown by Carbon

phplaravellaravel-5php-carbon

提问by Nathan

The following code throws an exception that I can't catch for whatever reason.

以下代码引发了一个我无法捕捉到的异常,无论出于何种原因。

try {
    $this->date = \Carbon\Carbon::parse($this->date)->toDateString();
}
catch (Exception $err) {
    $this->date = \Carbon\Carbon::parse("January 1st 1900")->toDateString();
}

Now, if I put this in my routes file in a function closure, it works fine. It's only throwing an exception when it's called from the Model.

现在,如果我把它放在我的路由文件中的函数闭包中,它工作正常。它仅在从模型调用时抛出异常。

exception 'Exception' with message 'DateTime::__construct(): Failed to parse time string (Summer 2015) at position 0 (S): The timezone could not be found in the database' in /home/vagrant/www/steamcompare/vendor/nesbot/carbon/src/Carbon/Carbon.php:222

exception 'Exception' with message 'DateTime::__construct(): Failed to parse time string (Summer 2015) at position 0 (S): The timezone could not be found in the database' in /home/vagrant/www/steamcompare/vendor/nesbot/carbon/src/Carbon/Carbon.php:222

Has anyone else had this issue with Carbon?

有没有其他人对碳有这个问题?

回答by Nathan

Immediately after posing the question, I thought of the answer. Since I saw a lot of posts online about a very similar issue, I figured I'd go ahead and answer this one.

提出问题后,我立即想到了答案。因为我在网上看到很多关于一个非常相似问题的帖子,所以我想我会继续回答这个问题。

The issue was namespacing. Carbon was running in a different namespace from my app (obviously) so when I tried to catch (Exception)I was actually trying to catch an exception within my app's namespace. Changing the catch statement to catch (\Exception)resolved it.

问题是命名空间。Carbon 运行在与我的应用程序不同的命名空间中(显然),因此当我尝试这样做时,catch (Exception)我实际上是在尝试在我的应用程序命名空间中捕获异常。更改 catch 语句以catch (\Exception)解决它。

I hope this helps anyone that ends up on this page.

我希望这对最终出现在此页面上的任何人都有帮助。