I am trying to add some error catching blocks in my Console app.
Specifically for example I have a SQL code block,
$query = "SELECT * FROM
visits_column_maps";
$mapsAry = Yii::$app->db->createCommand($query)->queryAll();
If something goes south an exception is thrown and the script ends.
I would like to catch this and end it on my terms.
I tried a try/catch block;
try {
$query = "SELECT * FROM
visits_column_maps";
$mapsAry = Yii::$app->db->createCommand($query)->queryAll();
} catch(Exception #e) {
// graceful exit here
echo "Exception caught";
exit();
}
but when tested by changing the table name I still get a script termination prior to catching it.
I suppose I may need to adjust a configuration somewhere but not really sure where.
Thanks for any help provided.
Scotty
you need to use \Exception instead of Exception
try {
$query = "SELECT * FROM
visits_column_maps";
$mapsAry = Yii::$app->db->createCommand($query)->queryAll();
} catch(\Exception $e) {
// graceful exit here
echo "Exception caught";
exit();
}
Related
I've got a (example) Oracle Stored Procedure:
CREATE OR REPLACE FUNCTION EXCEPTION_TEST
RETURN NUMBER
AS
BEGIN
raise_application_error(-20500, 'This is the exception text I want to print.');
END;
and I call it in PHP with PDO with the following code:
$statement = $conn->prepare('SELECT exception_test() FROM dual');
$statement->execute();
The call of the function works perfectly fine, but now I want to print the Exception text only.
I read somewhere, that you should not use try and catch with PDO. How can I do this?
You have read that you shouldn't catch an error to report it.
However, if you want to handle it somehow, it's all right to catch it.
Based on the example from my article on handling exception in PDO,
try {
$statement = $conn->prepare('SELECT exception_test() FROM dual');
$statement->execute();
} catch (PDOException $e) {
if ($e->getCode() == 20500 ) {
echo $e->getmessage();
} else {
throw $e;
}
}
Here you are either getting your particular error or re-throwing the exception back to make it handled the usual way
You check the execute response and get the error, for example, like this:
if ($statement->execute() != true) {
echo $statement->errorCode();
echo $statement->errorInfo();
}
You can find more options at the PDO manual.
I'm trying to customize error messages.
For handling errors i used "try/catch" block according to this Recurly documentation, like this for example:
try {
$account = Recurly_Account::get('my_account_id');
$subscription = new Recurly_Subscription();
$subscription->account = $account;
$subscription->plan_code = 'my_plan_code';
$subscription->coupon_code = 'my_coupon_code';
/* .. etc .. */
$subscription->create();
}
catch (Exception $e) {
$errorMsg = $e->getMessage();
print $errorMsg;
}
I wanted use code in catch block like this:
catch (Exception $e) {
$errorCode = $e->getCode();
print $myErrorMsg[$errorCode]; // array of my custom messages.
}
But getCode() method always returns zero for all possible errors.
My question for Recurly Team (or who there in this theme):
How i get error code for errors? Or please explain me how i can resolve this topic. Thanks!
If you look at the PHP Client on Github and you search for "throw new" which is what is done when an exception is thrown you'll see that they don't set the exception error code the second parameter of the exception constructor method.
Recurly PHP Client on Github: https://github.com/recurly/recurly-client-php/search?utf8=%E2%9C%93&q=throw+new
PHP Exception documentation: http://php.net/manual/en/language.exceptions.extending.php
Therefore, you'll either need to catch more exceptions based on their name
i.e.
catch (Recurly_NotFoundError $e) {
print 'Record could not be found';
}
OR
look at the exception message and compare it
catch (Exception $e) {
$errorMessage = $e->getMessage();
if($errorMessage=='Coupon is not redeemable.')
{
$myerrorCode=1;
}
//Add more else if, or case switch statement to handle the various errors you want to handle
print $myErrorMsg[$myerrorCode]; // array of my custom messages.
}
When I execute my script something went wrong and an exception is thrown, but instead of stop the all script. How can I tell to zend to continue ?
This error appear when I fetch a mail I have a try catch block but it doesn't catch.
Fatal error: Uncaught exception 'Zend\Mail\Exception\RuntimeException' with message 'Line "X-Assp-Message/IP-Score:
Thanks.
My code is a simple class to fetch mail :
$listm = new Zend\Mail\Storage\Pop3(array('host' => $this->mServer,'user' => $this->mMail, 'password' => $this->mPassword));
foreach ($listm as $msgp3)
{
try
{
e($msgp3->from);
e($msgp3->to);
e($msgp3->subject);
e($msgp3->date);
e(strtotime($msgp3->date));
e($msgp3->messageid);
} catch (Exception $e) {
e($e->getMessage());
}
}
And my code stop at the 10em mail, so how make to tell to Zend to doesn't stop ?
The point of an Exception is to tell you that something bad has happened, and you need to build code to handle that properly. Without seeing your code, it's kinda hard to debug though.
If you want not to stop a process when a exception has been pointed. You can use a try and catch method. Like this:
try {
DoSomethingReallyBad()
}
catch(RuntimeException $e) {
// do nothing
}
// go further
I must say when a exception is called. The process of your last task is quitted.
Note: I didn't test this!
How are you catching the exception? Can you supply the try/catch code in your question please?
In Zend you need to use the full zend exception class that is being thrown. In this case it is Zend\Mail\Exception\RuntimeException, which becomes Zend_Mail_Exception_RuntimeException.
try
{
// ...
}
catch (Zend_Mail_Exception_RuntimeException $e)
{
// ...
}
I finally found where was my problem :
The error is return when i fetch the message here so in the for instruction :
foreach ($listm **as $msgp3**)
To catch any error when the message is fetch i have to fetch this way :
$maxMessage = count($messageList);
for($i = 0; $i < $maxMessage; $i++)
{
try{
$msgp3 = $messageList->getMessage($i);
//--- WORK ON msgp3
}catch(Exception $e) {
echo 'E2->'.$e->getMessage();
}
}
And now my script continue...
This code works fine, but I'll want to handle exception if any thing goes wrong, so I deliberately made a syntax error in the query but nothing happens. Below is the code
try {
$sql = "INSERT INTO journals (topic, author, ) VALUES ('$topic', '$authors', ')";
echo "1st";
$lecturers_db->query($sql);
echo "second";
} catch(PDOException $e) {
echo $e->getMessage();
echo $msg = "Error!";
}
Without the obvious syntax error, the code works fine but with the syntax error, nothing happens, all the code in the try block executes and the code in the catch block never executes.
I want to raise an exception, please how do I do it here, thanks for any help.
Be sure to set the attribute PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION, as soon as you init your pdo object:
$lecturers_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
After that, any failed queries will raise an exception
Exceptions are thrown. Syntax errors in code != Exceptions.
<?php
try {
$code = 12;
throw new PDOException('Message', $code );
} catch (PDOException $e) {
}
?>
However, from the maual:
You should not throw a PDOException from your own code. See Exceptions
for more information about Exceptions in PHP.
My advice is to throw either a general exception, or to write your own custom exception to handle your error.
I have a page on my website (high traffic) that does an insert on every page load.
I am curious of the fastest and safest way to (catch an error) and continue if the system is not able to do the insert into MySQL. Should I use try/catch or die or something else. I want to make sure the insert happens but if for some reason it can't I want the page to continue to load anyway.
...
$db = mysql_select_db('mobile', $conn);
mysql_query("INSERT INTO redirects SET ua_string = '$ua_string'") or die('Error #10');
mysql_close($conn);
...
Checking the documentation shows that its returns false on an error. So use the return status rather than or die(). It will return false if it fails, which you can log (or whatever you want to do) and then continue.
$rv = mysql_query("INSERT INTO redirects SET ua_string = '$ua_string'");
if ( $rv === false ){
//handle the error here
}
//page continues loading
This can do the trick,
function createLog($data){
$file = "Your path/incompletejobs.txt";
$fh = fopen($file, 'a') or die("can't open file");
fwrite($fh,$data);
fclose($fh);
}
$qry="INSERT INTO redirects SET ua_string = '$ua_string'"
$result=mysql_query($qry);
if(!$result){
createLog(mysql_error());
}
You can implement throwing exceptions on mysql query fail on your own. What you need is to write a wrapper for mysql_query function, e.g.:
// user defined. corresponding MySQL errno for duplicate key entry
const MYSQL_DUPLICATE_KEY_ENTRY = 1022;
// user defined MySQL exceptions
class MySQLException extends Exception {}
class MySQLDuplicateKeyException extends MySQLException {}
function my_mysql_query($query, $conn=false) {
$res = mysql_query($query, $conn);
if (!$res) {
$errno = mysql_errno($conn);
$error = mysql_error($conn);
switch ($errno) {
case MYSQL_DUPLICATE_KEY_ENTRY:
throw new MySQLDuplicateKeyException($error, $errno);
break;
default:
throw MySQLException($error, $errno);
break;
}
}
// ...
// doing something
// ...
if ($something_is_wrong) {
throw new Exception("Logic exception while performing query result processing");
}
}
try {
mysql_query("INSERT INTO redirects SET ua_string = '$ua_string'")
}
catch (MySQLDuplicateKeyException $e) {
// duplicate entry exception
$e->getMessage();
}
catch (MySQLException $e) {
// other mysql exception (not duplicate key entry)
$e->getMessage();
}
catch (Exception $e) {
// not a MySQL exception
$e->getMessage();
}
if you want to log the error etc you should use try/catch, if you dont; just put # before mysql_query
edit :
you can use try catch like this; so you can log the error and let the page continue to load
function throw_ex($er){
throw new Exception($er);
}
try {
mysql_connect(localhost,'user','pass');
mysql_select_db('test');
$q = mysql_query('select * from asdasda') or throw_ex(mysql_error());
}
catch(exception $e) {
echo "ex: ".$e;
}
Elaborating on yasaluyari's answer I would stick with something like this:
We can just modify our mysql_query as follows:
function mysql_catchquery($query,$emsg='Error submitting the query'){
if ($result=mysql_query($query)) return $result;
else throw new Exception($emsg);
}
Now we can simply use it like this, some good example:
try {
mysql_catchquery('CREATE TEMPORARY TABLE a (ID int(6))');
mysql_catchquery('insert into a values(666),(418),(93)');
mysql_catchquery('insert into b(ID, name) select a.ID, c.name from a join c on a.ID=c.ID');
$result=mysql_catchquery('select * from d where ID=7777777');
while ($tmp=mysql_fetch_assoc($result)) { ... }
} catch (Exception $e) {
echo $e->getMessage();
}
Note how beautiful it is. Whenever any of the qq fails we gtfo with our errors. And you can also note that we don't need now to store the state of the writing queries into a $result variable for verification, because our function now handles it by itself. And the same way it handles the selects, it just assigns the result to a variable as does the normal function, yet handles the errors within itself.
Also note, we don't need to show the actual errors since they bear huge security risk, especially so with this outdated extension. That is why our default will be just fine most of the time. Yet, if we do want to notify the user for some particular query error, we can always pass the second parameter to display our custom error message.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
I am not sure if there is a mysql version of this but adding this line of code allows throwing mysqli_sql_exception.
I know, passed a lot of time and the question is already checked answered but I got a different answer and it may be helpful.
$sql = "INSERT INTO customer(FIELDS)VALUES(VALUES)";
mysql_query($sql);
if (mysql_errno())
{
echo "<script>alert('License already registered');location.replace('customerform.html');</script>";
}
To catch specific error in Mysqli
$conn = ...;
$q = "INSERT INTO redirects (ua_string) VALUES ('$ua_string')";
if (mysqli_query($conn, $q)) {
// Successful
}
else {
die('Mysqli Error: '.$conn->error); // Show Error Complete Description
}
mysqli_close($conn);
Use any method described in the previous post to somehow catch the mysql error.
Most common is:
$res = mysql_query('bla');
if ($res===false) {
//error
die();
}
//normal page
This would also work:
function error() {
//error
die()
}
$res = mysql_query('bla') or error();
//normal page
try { ... } catch {Exception $e) { .... } will not work!
Note: Not directly related to you question but I think it would much more better if you display something usefull to the user. I would never revisit a website that just displays a blank screen or any mysterious error message.
$new_user = new User($user);
$mapper = $this->spot->mapper("App\User");
try{
$id = $mapper->save($new_user);
}catch(Exception $exception){
$data["error"] = true;
$data["message"] = "Error while insertion. Erron in the query";
$data["data"] = $exception->getMessage();
return $response->withStatus(409)
->withHeader("Content-Type", "application/json")
->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
}
if error occurs, you will get something like this->
{
"error": true,
"message": "Error while insertion. Erron in the query",
"data": "An exception occurred while executing 'INSERT INTO \"user\" (...) VALUES (...)' with params [...]:\n\nSQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for integer: \"default\"" }
with status code:409.