When the following gets bad data PHP aborts.
PHP Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct(): Failed to parse time string (980671) at position 4 (7): Unexpected character'
How can I catch this if the data is bad to take other action so the PHP problem doesn't fail?
$date = new DateTime($TRANSACTION_DATE_MMDDYY_raw);
Use try and catch
try {
$date = new DateTime($date);
} catch(Exception $e) {
echo "Invalid date... {$e->getMessage()}";
}
As #Rob W already said, you gotta catch that exception.
But what could cause that exception is inaproppriate datetime format.
To solve this, you could do instead:
try {
$dt = DateTime::createFromFormat("MMDDYY", $TRANSACTION_DATE_MMDDYY_raw) ;
} catch(Exception $e){
echo "Something went wrong: {$e->getMessage()} " ;
}
More about it: http://www.php.net/manual/en/datetime.createfromformat.php
Related
i have a simple class:
public function CreateCustomer()
{
.
.
try{
$birthDate = Carbon::parse($birth)->toIso8601String();
}catch (\Exception $ex){
die("error");
}
And on top of the controller:
use Exception;
I get an error that the exception was Not caught
InvalidArgumentException
Unexpected data found. Trailing data
i've even tried to catch "InvalidArgumentException", but no luck
Found the error, it was on
->toIso8601String();
As it was generating a double, uncaught exception
My code snippet is below - as you can see, I have a try-catch block, but inspite of this, I still get an uncaught exception that terminates the entire application. What am I missing?
try {
$cakeXml = simplexml_load_string($xml);
$parseSuccess = $cakeXml->xpath('//ParseSuccess');
} catch (Exception $ex) {
$response['parseSuccess'] = false;
$response['errors']['ParseError'] = 'An unknown error occurred while trying to parse the file. Please try again';
return $response;
}
2014-12-16 22:45:12 Error: Fatal Error (1): Call to a member function xpath() on a non-object
2014-12-16 22:45:12 Error: [FatalErrorException] Call to a member function xpath() on a non-object
If you read the error message more-carefully, you will see that it is not dieing on an Exception, but on a Fatal Error. A try/catch statement cannot catch a fatal error in PHP, as there is no way to recover from a fatal error.
As for solving this issue, your error is telling you $cakeXml is a non-object. One solution would be to do something like this.
try {
$cakeXml = simplexml_load_string($xml);
if (!is_object($cakeXml)) {
throw new Exception('simplexml_load_string returned non-object');
}
$parseSuccess = $cakeXml->xpath('//ParseSuccess');
} catch (Exception $ex) {
$response['parseSuccess'] = false;
$response['errors']['ParseError'] = 'An unknown error occurred while trying to parse the file. Please try again';
return $response;
}
DOMXPath methods i.e. xpath or evaluate does not throw exceptions. Hence, you will need to explicitly validate and throw the exception.
See below code snippet:
$xml_1= "";
try {
$cakeXml = simplexml_load_string($xml_1);
if ( !is_object($cakeXml) ) {
throw new Exception(sprintf('Not an object (Object: %s)', var_export($cakeXml, true)));
} else {
$parseSuccess = $cakeXml->xpath('//pages');
print('<pre>');print_r($parseSuccess);
}
} catch (Exception $ex) {
echo 'Caught exception: ', $ex->getMessage(), "\n";
}
i've try this example :
<?php
try {
Not_Exist();
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>
http://php.net/manual/en/language.exceptions.php
But the error is not catched :
Fatal error: Call to undefined function Not_Exist() in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC9\data\localweb\mysite\public_html\exception.php on line 3
Why? I'm usually using Dotnet. Maybe i miss something.
error is not an exception. PHP itself doesn't throw exceptions on syntax errors, such as missing functions. You'd need set_error_handler() to "catch" such things - and even then, a custom error handler can't handle parse errors such as this.
There is no Exception being thrown in your code. You're simply hitting a fatal error. If you're trying to find a way around fatal errors, this post may be of help. How do I catch a PHP Fatal Error
If you're trying to catch Exceptions, something like this:
try {
throw new Exception("Exception Message");
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
Because that is a fatal error, not an exception. You're going to want to use PHP's function_exists() method and try something like:
try{
function_exists(Not_Exist);
} catch (Exception $e) {
// error here
}
// run Not_Exist here because we know its a valid function.
When I try to process url http://www.bbc.co.uk/ dompdf throws error
fatal error: Uncaught exception 'DOMPDF_Exception' with message 'Box property calculation requires containing block width' in www\dompdf\include\block_frame_reflower.cls.php on line 171
It seems some settings or some bug?
DOMPDF_Exception is an extension of the Exception class. I'm not sure what parameters it will spit out, but you can dump the array out to see what is being returned:
try{
}catch(DOMPDF_Exception $e){
echo '<pre>',print_r($e),'</pre>';
}
Also found this on Google Code that might help you narrow down, what the actual issue is: http://code.google.com/p/dompdf/issues/detail?id=244
No, you just have to catch exceptions or set your stuff properly.
try {
//Do your stuff here
} catch (Exception $e){
echo $e->message() ;
}
I believe the correct way to return the message is
try {
//Do your stuff here
} catch (Exception $e){
echo $e->getMessage() ;
}
Does anybody know why this function, when passed an invalid date (e.g. timestamp) to it, still throws an error despite the try-catch?
function getAge($date){
try {
$dobObject = new DateTime($date);
$nowObject = new DateTime();
$diff = $dobObject->diff($nowObject);
}
catch (Exception $e) {
echo 'Error: ', $e->getMessage();
}
return $diff->y;
}
Error:
Fatal error: Uncaught exception 'Exception' with message 'DateTime::_construct() [datetime.--construct]: Failed to parse time string (422926860) at position 7 (6): Unexpected character' in ... .php:4 Stack trace: #0 ... .php(4): DateTime->_construct('422926860') #1 ... .php(424): getAge('422926860') #2 {main} thrown in/... .php on line 4
Thank you very much in advance!
Chris, you cannot catch fatal errors, at very least you shouldn't.
Quoting keparo:
PHP won't provide you with any conventional means for catching fatal errors because they really shouldn't be caught. That is to say, you should not attempt to recover from a fatal error. String matching an output buffer is definitely ill-advised.
If you simply have no other way, take a look at this post for more info and possible how-tos.
Try this:
function isDateValid($str) {
if (!is_string($str)) {
return false;
}
$stamp = strtotime($str);
if (!is_numeric($stamp)) {
return false;
}
if ( checkdate(date('m', $stamp), date('d', $stamp), date('Y', $stamp)) ) {
return true;
}
return false;
}
And then :
if isDateValid( $yourString ) {
$date = new DateTime($yourString);
}