Can't catch Exception thrown by Carbon
Asked Answered
S

1

20

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

Has anyone else had this issue with Carbon?

Sawtelle answered 6/7, 2015 at 14:33 Comment(0)
S
58

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.

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

Sawtelle answered 6/7, 2015 at 14:39 Comment(9)
You should mark your answer as the correct answer while you're here answering your question :)Geny
I will, once the timer that SO puts on a question goes away.Sawtelle
Ahh sorry didn't realise there was one.Geny
No worries, you have to wait 48 hours before you can accept your own answer. =/Sawtelle
I suppose it's there to stop people artificially upping their score by asking and answering their own questions loads and loads.Geny
One frickin' backslash …Genetic
@Geny i don't know, you can actually even post "question" with "answer" type of post on stackoverflow. it can't be for score neither, because it is really trivial to figure out whether has the question been answered by the original author. plus, you can even answer it laterAllegorical
This doesn't solve the problem. Carbon::parse generates PHP warnings, so you cannot catch it using try .. catchRichia
@Richia this is a 7 year old post and the provided solution DID work. If it no longer works that would be due to changes in Carbon.Sawtelle

© 2022 - 2024 — McMap. All rights reserved.