I have an exception class that looks like this
<?php
class Errors{
public function displayError(Exception $e){
$trace = $e->getTrace();
if($trace[0]['class'] != ""){
$class = $trace[0]['class'];
$method = $trace[0]['function'];
$file = $trace[0]['file'];
$line = $trace[0]['line'];
$error_message = $e->getMessage().
"<br /> Class/Method : ".$class." <==> ".$method.
"<br /> File : ".$file.
"<br /> Line : ".$line;
}
return $error_message;
}
}
?>
This works fine for many errors that are thrown due do typos/column count not matching value count, but when I throw an exception from the code myself, I get an error. For example
try{
$stmt = $db->dbh->prepare("SELECT user FROM reset ");
$stmt->execute();
if ($stmt->rowCount() < 1){
throw new Exception('The Link expired, request a new one');
} else {
throw new Exception('The Link is invalid, please request a new one');
}
}
catch (PDOException $e) {
$error = new Errors();
echo "<b>".$error->displayError($e)."</b>";
}
I get Uncaught exception 'Exception' with message 'The Link is invalid, please request a new one' error when I run the code. If I remove that line, and induce an error by spelling SELECT as SLECT, the error class works fine.
How can I make in such a way that the error class will catch all types of errors ?
The problem is NOT all exceptions are PDOExceptions.You code cacthes only PDOException which means new Exception won't be catched. Try :
try
{
$stmt = $db->dbh->prepare("SELECT user FROM reset ");
...
}
catch (PDOException $e)
{
$error = new Errors();
echo "<b>".$error->displayError($e)."</b>";
}
catch (Exception $e)
{
$error = new Errors();
echo "<b>".$error->displayError($e)."</b>";
}
The reason why your code works when you spell SELECT as SLECT is because you triggered a PDOException instead of a new Exception.
Related
when executing the form, the data is not inserting. I have activated SQLITE3 and I am not skipping any type of error.
The echo of the try is to see what was wrong but nothing. I see everything right.
Does anyone help me?
$username = $_POST['nombre'];
$clave = $_POST['clave'];
$apenom = $_POST['apenom'];
try {
$bd = new SQLite3("test");
//preparamos la sentencia
echo "INSERT INTO usuarios (username,clave,apenom) VALUES ('$username','$clave','$apenom')";
$bd->exec("INSERT INTO usuarios (username,clave,apenom) VALUES ('$username','$clave','$apenom')");
/* while ($row = $resultado->fetchArray()) {
echo "{$row['username']} {$row['clave']} {$row['apenom']} \n";
} */
} catch (\Throwable $th) {
echo $th;
}
Do take the advice from the comments into account, database security is not something you should 'wing'...
As for a little help on setting up a connection and importantly debugging if anything goes wrong so you know what to fix, the following 'skeleton' might help:
<?php
try {
// connect to your database
$sqlite = new SQLite3('test.db');
}
catch (Exception $e) {
// if no connection could be established a exception is thrown
echo $e->getMessage();
}
// your query
$query = '...';
$result = $sqlite->query($query); // result object (FALSE on error)
if (!$result) {
// query failed for some reason...
echo $sqlite->lastErrorMsg();
} else {
// do something with result
}
I have to try-catch block for stripe payment to handle error responses, Now I am using laravel to code.
But after catching it gives me 500 internal server error, instead of storing an exception message, it catches the error with 500 Internal Server?
Here is my code:
try {
$customer = \Stripe\Customer::create([
'email' => $email,
'source' => $token,
]);
$customer_id = $customer->id;
$subscription = \Stripe\Subscription::create([
'customer' => $customer_id,
'items' => [['plan' => 'plan_id']], //plan-id is static as there is single plan
]);
$chargeJson = $subscription->jsonSerialize();
}
catch(Stripe_CardError $e) {
$error = $e->getMessage();
} catch (Stripe_InvalidRequestError $e) {
// Invalid parameters were supplied to Stripe's API
$error = $e->getMessage();
} catch (Stripe_AuthenticationError $e) {
// Authentication with Stripe's API failed
$error = $e->getMessage();
} catch (Stripe_ApiConnectionError $e) {
// Network communication with Stripe failed
$error = $e->getMessage();
} catch (Stripe_Error $e) {
// Display a very generic error to the user, and maybe send
// yourself an email
$error = $e->getMessage();
} catch (Exception $e) {
// Something else happened, completely unrelated to Stripe
$error = $e->getMessage();
}
$resp = array();
if(isset($chargeJson) && !empty($chargeJson['id'])) {
$resp['status'] = 1;
$resp['transactions_log'] = $chargeJson;
$resp['current_period_end'] = $chargeJson['current_period_end'];
$resp['transaction_id'] = $chargeJson['id']; // which is actually subcsription id
} else {
$resp['status'] = 0;
$resp['error'] = $error;
}
return $resp;
I am not sure how to handle it and store it.
I am pretty much sure I have catched the exception but I can't store it and further use it.
I am trying catch database errors within a transaction and if one occurs then rollback and throw an exception.
However, the code is stopping and displaying the db error screen before it throws the exception.
Any ideas how I can make it detect db error without stopping running the subsequent code?
try {
$this->my_function($data);
} catch (Exception $e) {
var_dump($e);
}
private function my_function($data)
{
$this->db->trans_start();
foreach($data as $reg)
{
$sql = $this->db->insert_string('my_table', $reg);
if($this->db->query($sql))
{
continue;
} else {
$this->db->trans_rollback();
throw new Exception('Exception message here...');
}
}
$this->db->trans_complete();
}
This has been answered before on this question
As answered by cwallenpoole:
In application/config/database.php set
// suppress error output to the screen
$db['default']['db_debug'] = FALSE;
In your model or controller:
// try the select.
$dbRet = $this->db->select($table, $dataArray);
// select has had some problem.
if( !$dbRet )
{
$errNo = $this->db->_error_number()
$errMess = $this->db->_error_message();
// Do something with the error message or just show_404();
}
Or in you case:
private function my_function($data)
{
$errors = array();
$this->db->trans_start();
foreach($data as $reg)
{
$sql = $this->db->insert_string('my_table', $reg);
if($this->db->query($sql))
{
continue;
} else {
$errNo = $this->db->_error_number()
$errMess = $this->db->_error_message();
array_push($errors, array($errNo, $errMess));
}
}
$this->db->trans_complete();
// use $errors...
}
Even better
I believe this question has all the answers you need because it takes multiple inserts into account and let's you finish the once that did not return an error.
I have tried this piece of code and unfortunately rollback method failed!
Thank in advance!!
$bash = new mysqli('localhost', 'root', '','dbastegoi');
$bash->autocommit(FALSE);
echo 'timologio';
$r =$bash->query("INSERT INTO tbparastatika (strArithmos, fkERGO, strPROMITH, sngCOST, intTYPOS, intDRASH) VALUES ('1','1001','123123123',800138,1,1)");
//ΕΙΣΑΓΩΓΗ ΤΙΜΟΛΟΓΙΟΥ
$i = $bash->insert_id;
ECHO PHP_EOL;
echo 'dapanh';
try {
$r =$bash->query("INSERT INTO tbdapanes_stegash (idPARASTATnIKO, sngCOST, fkDIAMERISMA, intMONTH) VALUES ($i,100,1,1)");
echo $r;
} catch (Exception $e) {
echo 'error2';
}
$bash->commit();
$bash->rollback();
//$SYNDESH->commit();
//$SYNDESH->rollback();
$bash->close();
You can not make a commit first and then a roolback. You have to make a commit if your query runs without error or make a rollback if you get an error:
try {
$r =$bash->query("INSERT INTO tbdapanes_stegash (idPARASTATnIKO, sngCOST, fkDIAMERISMA, intMONTH) VALUES ($i,100,1,1)");
echo $r;
$bash->commit();
} catch (Exception $e) {
echo 'error2';
$bash->rollback();
}
I M Using YII to develop web application
i want to check if query executed successfully or not
$data = Yii::app()->db->createCommand($SQL);
$result = $data->queryAll();
if(count($result) == 0)
{
throw new SoapFault('Sender', 'Unable to get display information.');
}
if code will execute if select query return no result-set. but i want to check if query executed successfully or not. based on that i want to throw exception. then if query executed successfully and returned no result-set then some other exception.
how to do this ? any suggestions ?
try {
$result = $data->queryAll();
} catch (Exception $ex) {
echo 'Query failed', $ex->getMessage();
}
try
{
$result = Yii::app()->db->createCommand($sqlQuery)->execute();
echo 'success';
}
catch (Exception $e)
{
echo 'fail';
}