try and catch PDO because he might escape with exception $e - pdo

Every tutorial online uses try and catch on any insert and update query by PDO.
However, all the tutorial do not stop and explain why the value in pdoexception is $e?
try {
$db->query('SELECT * FROM mypants ORDER by thebiggest');
} catch(PDOException $e) {
echo "too small"; //user friendly message
}
Why am I asking this stupid question? because I do not see a variable $e elsewhere!? why do we have to put $e beside the PDOEXEPTION? what does it do exactly? do I need to change the variable on every try and catch that I excute??

This line:
} catch(PDOException $e) {
... means catch an exception that is an instance of PDOException, and assign it to $e
To answer your question, $e doesn't already exist, it is assigned when the exception is caught. Once the exception occurs $e will contain information about the exception which you can use for debugging, logging, or displaying to the screen.
$e is just a convention, you could call the variable whatever you like, and you don't need to worry about changing the variable on every try catch

$e is the variable you want to put the exception in. It's not using an existing variable; it's similar to this:
$v = 6;
There, $v didn't exist before; the name only really matters to the code that uses it later.

Related

How to skip particular WebElement process when locator is not found?

prinBalAgencyComm.sendKeys(testData.get("agencyCommissionPB"));
prinBalClientRem.sendKeys(Keys.TAB);
prinBalFrom2.sendKeys(testData.get("fromFB2")); //Locator not found
prinBalAgencyCommLast.sendKeys(testData.get("agencyCommissionLastPB")); //how to execute this line without fail
You can handle this by using try catch finally.
try{
//code that can result in an exception
prinBalAgencyComm.sendKeys(testData.get("agencyCommissionPB"));
prinBalClientRem.sendKeys(Keys.TAB);
prinBalFrom2.sendKeys(testData.get("fromFB2"));
}catch(Exception e)
{
//actions you want to take in case your locator isnt found or another exception occurs
System.out.println("Exception occured" + e.getMessage());
}finally
{ //the line to be executed without fail
prinBalAgencyCommLast.sendKeys(testData.get("agencyCommissionLastPB"));
}
you would have to implement a try/catch block
try {
element action
} catch (Exception e) {
//whatever you want to happen when it fails
}`
But I would ask myself why is the test not consistent with every run? Why should this step not pass every time?
One pattern you can use is:
try {}
catch {}
Place your offending code in the try block and any error code in the catch block.
If an exception is raised in the try, the catch block will be called instead of proceeding to the next line in the try

Intellij: create a random number via IDE to use as error number / error code?

see here: The proper way to do exception handling
say this code:
function changeBookAuthor(int $id, string $newName){
if(!$newName){
throw new MyAppException('No author name was provided');
}
$book = Books::find($id);
if(!$book){
throw new MyAppException('The provided book id could not be found');
}
//..
}
i want to change that to:
function changeBookAuthor(int $id, string $newName){
if(!$newName){
throw new MyAppException('No author name was provided', <SOMEVERYRANDOMNUMBER>);
}
$book = Books::find($id);
if(!$book){
throw new MyAppException('The provided book id could not be found', <SOMEVERYRANDOMNUMBER>);
}
//..
}
can intellij help me in selecting random numbers?
I personally use different types of Exception instead of exception code.
For example:
try{
...
} catch (PDOException e1){
// Show a message that we could not do SQL work
} catch (NumberFormatException e2){
// Show a message that input was not a valid number
} catch (Exception e){
// I'm not sure what was wrong but definitely there was some thing wrong
}
But if you still want random numbers, go to https://www.random.org, there are some number generators, copy values and define them as constants in your code (i guess that you are using PHP)

How do I catch a query exception in laravel to see if it fails?

All I'm trying to do is verify a query.
'SELECT * from table_that_does_not_exist'
Without that erroring out, I'd like to know it failed so I can return a response that states "Error: table does not exist" or the generic error.
The simplest way to catch any sql syntax or query errors is to catch an Illuminate\Database\QueryException after providing closure to your query:
try {
$results = \DB::connection("example")
->select(\DB::raw("SELECT * FROM unknown_table"))
->first();
// Closures include ->first(), ->get(), ->pluck(), etc.
} catch(\Illuminate\Database\QueryException $ex){
dd($ex->getMessage());
// Note any method of class PDOException can be called on $ex.
}
If there are any errors, the program will die(var_dump(...)) whatever it needs to.
Note: For namespacing, you need to first \ if the class is not included as a use statement.
Also for reference:
Laravel 5.5 API - Query Exception
Laravel 8.x API - Query Exception
Wrap the lines of code you wish to catch an exception on using try-catch statements
try
{
//write your codes here
}
catch(Exception $e)
{
dd($e->getMessage());
}
Do not forget to include the Exception class at the top of your controller by saying
Use Exception;
If you want to catch all types of database exceptions you can catch it on laravel Exception Handler
if ($exception instanceof \PDOException) {
# render a custom error
}
for more details about how to use laravel Exception Handler check https://laravel.com/docs/7.x/errors
Laravel 8.x
try {
$model->save(); // Use Eloquent: https://laravel.com/docs/8.x/eloquent
} catch (\Throwable $e) {
return 'My error message';
}
Note* Need to specify \Throwable $e no Throwable $e.

PDO error handling [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 5 years ago.
From a tutorial on the intertubes I learned a bit about doing PDO queries. The tutorial used try/catch and the queries are basically structured like so:
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $user, $pass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$stmt = $dbh->prepare("UPDATE users yada yada yadda");
$stmt->bindParam(':param1', $param1, PDO::PARAM_INT);
$stmt->bindParam(':param2', $param2, PDO::PARAM_INT);
$stmt->execute();
}
catch(PDOException $e)
{
echo $e->getMessage();
}
This of course echos mysql errors on the screen. Not that I intend on having bad queries, but I do not like the idea of echoing out errors right on the screen, figuring what if an attacker tries to induce said errors and try to learn something from them.
Is there a better way to do this so that any errors go to a log file instead, or do I in actuality have nothing to fear in this regard since the bound parameters eliminate the risk of any sql injection?
The tutorial is correct in that you want to use try..catch blocks to catch code that will possibly cause an error and bring down whatever you're loading. So, if you have some code that is dependent on this code executing you'd want to include it in your try section. If you absolutely need this code to execute for whatever you're creating to work, then you'll probably want to catch the error and redirect the user to some type of error page.
If you use the php error log function then instead of
echo $e->getMessage();
You can use
error_log($e->getMessage(),0);
to send the error message from PDO directly to your php error log. If you don't know where the error log is, you can check out this link for a couple pointers to it if you're running a *nix system. If you're running windows there should be a config file somewhere that will tell you. Or you can check the php ini file for the location it's pointing to for a surefire way to find the log.
Is there a better way to do this
Yes, sure!
That's apparently wrong way of handling PDO errors this tutorial taught you.
So, just get rid of these try..catch commands - that's all.
This way you'll have PDO exceptions handled the same way as other PHP errors. Thus, in case of query error your script will be halted and error will be logged (if you tell PHP so).
To tell PHP so, you have to set log_errors ini directive to 1
To tell PHP not to show errors on-screen, set display_errors ini directive to 0 (on a development server you may wish to reverse them though)
Well, my answer probably not in the best practice, so please leave it to the last option. But for my case, it works perfectly.
PDO::__construct however will give you an exception anyway no matter what you set in PDO::ATTR_ERRMODE. I don't know why they design it to behave like that.
My way to solve this problem is to create a code area i call it Debug Critical Section (means you need very careful about the codes in the section), any errors in this section will not directly output to user.
Here is the code i made for my framework:
private function doPDOConnect($dbIndex, &$DBInfo, &$error) {
$dbh = null;
$successed = false;
if (!isset($this->connectedDB[$dbIndex])) {
// Enter Critical Section so no error below belowing code will cause error output, but the error still in log though
facula::core('debug')->criticalSection(true);
try {
$dbh = new PDO($DBInfo['Driver'] . ':' . $DBInfo['Connection'] . '=' . $DBInfo['Host'] . ';dbname=' . $DBInfo['Database'], $DBInfo['Username'], $DBInfo['Password'], array( PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING, PDO::ATTR_TIMEOUT => $DBInfo['Timeout'] )); // ATTR_ERRMODE => PDO::ERRMODE_WARNING. or we will cannot get anything even error happens
$dbh->facula_prefix = $DBInfo['Prefix'];
$dbh->facula_index = $dbIndex;
$dbh->facula_connection = $DBInfo; // In order you want to reconnect this specify database after connection lost etc, remove if you worry about the security issue.
$successed = true;
} catch (PDOException $e) {
$error = $e->getMessage(); // If any error, catch it, to &$error.
}
// Exit Critical Section, restore error caught
facula::core('debug')->criticalSection(false);
if ($successed) {
return $this->connectedDB[$dbIndex] = $dbh;
}
} else {
return $this->connectedDB[$dbIndex];
}
return false;
}
So in your case, you may replace my facula::core('debug')->criticalSection to display_errors off/on to handle the error display handler correctly.
For example:
$display_error_status = ini_get('display_errors');
function criticalSection($entered) {
global $display_error_status;
if ($entered) {
ini_set('display_errors', '0');
} else {
ini_set('display_errors', $display_error_status);
}
}

InvalidOperationException is ignored in try/catch block

I have the following coding
try
{
var foundCanProperty = properties
.First(x => x.Name == "Can" + method.Name);
var foundOnExecuteMethod = methods
.First(x => x.Name == "On" + method.Name);
var command = new Command(this, foundOnExecuteMethod, foundCanProperty);
TrySetCommand(foundControl as Control, command);
}
catch (InvalidOperationException ex)
{
throw new FatalException("Please check if you have provided all 'On' and 'Can' methods/properties for the view" + View.GetType().FullName, ex);
}
I'd expected that if the methods.First() (in second var statement) throws an InvalidOperationException, I'd be able to catch it. But this seems not be the case (catch block is ignored and the application terminates with the raised exception). If I throw myself an exception of the same type within the try block, it gets caught. Does Linq use multihreading so that the exception is thrown in another thread? Perhaps I make also a stupid error here and just do not see it :(.
Thanks for any help!
I know that this isn't an answer, but rather some additional steps for debugging, but does it change anything if you instead try to catch the general type "Exception" instead of the IOE? That may help to isolate if the method is truly throwing an IOE, or if its failure is generating an IOE somewhere else in the stack. Also - assuming this method isn't in main() - is there a way to wrap the call to it in a try/catch and then inspect the behavior at that point in the call flow?
Apologies, too, in that I know very little about the SilverLight development environment so hopefully the suggestions aren't far fetched.
InvalidOperationException exception occures when The source sequence is empty.
refere to http://msdn.microsoft.com/en-us/library/bb291976.aspx
check weather "properties" or "methods" is not empty.
out of interest, Why you not using FirstOrDefault ?