PHP exception handling - error not being catch - php

So I have the following code:
try {
if ($connectionid = ldap_connect($ldapserver)) {
$ldapbindid=ldap_bind($connectionid, $binddn, $bindpw);
if ($mysearch = ldap_search($connectionid, $basedn, $query)) {
//more LDAP code here
}
} else {
return false;
}
} catch (Exception $exception) {
return false;
}
But because I'm supplying the wrong binddn and password, I'm getting a PHP error in the ldap_bind command.
Warning: ldap_bind(): Unable to bind to server: Invalid credentials
But reading my code, I understand I should get a boolean instead?
I have the impression that any errors that happens within the confines of the "try" section is going to be handled by the "catch" section. perhaps I'm understanding try/catch incorrectly?
Thanks a lot

Related

dns_get_record(): A temporary server error occurred.

I'm querying a whole bunch of addresses, some are online and some are not. I can't seem to get around this error however, even catching the exception fails :(
dns_get_record(): A temporary server error occurred.
try {
$result = dns_get_record('_minecraft._tcp.' . $addr, DNS_SRV);
}
catch (Exception $e) {
return [$addr,$port];
}
If this error occurs, I want to continue the script, skipping the record, however currently the script just halts.
Any help appreciated!!
I can't catch this exception too. And how I understood it's a bug of php:
https://bugs.php.net/bug.php?id=73149
But I found another solution. You can use # when you call this function. This symbol kill all errors when you call this one. And it will looks like that:
$dns = #dns_get_record($domain, DNS_A);
if(!$dns){
return false;
}
I was able to get the IP (A record) for a host using the below PHP function
gethostbynamel(string $hostname): array|false
Reference: gethostbynamel — Get a list of IPv4 addresses corresponding to a given Internet host name
try this:
try {
$dns = dns_get_record($domain, DNS_A);
}
catch (Exception $e) {
if ($e->getMessage() !== 'dns_get_record(): A temporary server error occurred.') {
throw $e;
}
$dns = false;
}

ZF1 Get errors before redirect

As the title says, I want to get all errors before the redirect. So this is my case:
I have a select for changing databases(identical structure but different data);
So let's say I am here: localhost/user/edit/id/100 (database 1)
on db change, I am redirecting the user to the same page, but we load data from database 2.
If it is not found, I get an error:
"Fatal error: Call to a member function on a non-object ..."
How do I catch the errors before the redirect occurs in order to change the url?
Thanks!
Use try {} catch() {} for catching errors before redirect.
try {
if (/* if error occured */) {
throw new \Exception('Error occured');
}
} catch(\Exception $e) {
// redirect with error occured
}
// redirect without error
In Zend maybe need to use return $redirectObj, I don't know Zend well.
In your case, try to do this:
try {
if ( ! $this->getResponse()) {
throw new Exception('Error occured! Can not get response object');
}
return $this->getResponse()->setRedirect($url);
} catch (Exception $e) {
echo $e->getMessage();
die();
}

libcouchbase connection errors

Couchbase keeps complaining that I don't have a connection to Couchbase:
2013-10-28T11:15:46.580320-07:00 hoot77 apache2[30455]: PHP Warning: There is no active connection to couchbase in /ebs1/www/src/core/components/In/Couchbase/Bucket.php on line 112
The following is the piece of code that is trying to run, its a simple set.
*/
public function set($key, $doc, $try = 0) {
// Make sure designDoc and dataView are set
if(empty($this->designDoc) && empty($this->dataView)) {
throw new In_Exception('Missing Design Doc and/or View name for Couchbase', 400);
}
try {
$results = $this->cb->set($key, $doc);
} catch(CouchbaseLibcouchbaseException $e) {
// Connection not active, try to rebuild connection and query again
// Log stats on exception
Statsd::increment("web.Couchbase.Exception.LibCouchbaseException.{$this->instanceKey}");
Logger::error("LibCouchbaseException on {$this->instanceKey}: {$e->getMessage()}");
// Try to reconnect and query up to twice
$try++;
if($try <= 2) {
$this->rebuildConnection();
return $this->set($key, $doc, $try);
} else {
// Fail if we've already tried twice
throw new In_Exception('Could not connect to Couchbase', 500);
}
} catch(CouchbaseException $e) {
// Catch general exception, try to determine cause
// Log stats on exception
Statsd::increment("web.Couchbase.Exception.CouchbaseException.{$this->instanceKey}");
Logger::error("CouchbaseException on {$this->instanceKey}: {$e->getMessage()}");
// Throw exception if design document or view not found
if($this->getExceptionCode($e->getMessage()) == 404) {
throw new In_Exception('Design Document, or View not found in Couchbase', 404);
} else {
throw new In_Exception('Error with Couchbase, try again.', 500);
}
}
// Success, return results
Statsd::increment("web.couchbase.{$this->instanceKey}.success");
return $results;
}
The line that its complaining about is:
$results = $this->cb->set($key, $doc);
You can see that my quick solution was to try to reconnect up to twice on failure, but that doesn't seem to be helping at all, the errors still persist in great numbers.
It's actually not catching the exceptions and reporting them consistently either, which is annoying, because PHP is throwing these as warnings, not exceptions.
Let me know if you have any suggestions as to how to solve this, it would be greatly appreciated. Thanks!

Mysqli php i want a custom error message when unknown server host

I am writing a script to install the database of an application in php. It working fine but when im trying to install a database that doesnt exist i want only my own error message but i keep getting the default Warning : Warning: mysqli::mysqli() [mysqli.mysqli]: (HY000/2005): Unknown MySQL server host 'kasdasd'.
So I know that the host is wrong and I want it to be so, with only my own errormessage. How do I get rid of this message?
My connectclass with parameter DBConfig $config:
$this->mysqli = new mysqli($config->m_host,
$config->m_user,
$config->m_passw,
$config->m_db);
if ($this->mysqli->connect_error) {
return false;
}
$this->mysqli->set_charset("utf8");
return true;
an easy solution would be to see if you can open the hostname using fsockopen and suppressing the errors:
$port = 80;
if($fp = #fsockopen($config->m_host,$port)){
$db = new mysqli($config->m_host,$config->m_user,$config->m_passw,$config->m_db);
}else{
echo 'hostname not recognized';
}
#fclose($fp);
Edited:
You can use
if ($mysqli->connect_error) {
/** handle your error here **/
// Throw a custom exception if you like! (see below)
// or just echo "There was an error";
}
You can further use mysqli_connect_errno() to find out wht happened and handle it accordingly.
Edit: mysqli doesn't throw erros so below is incorrect.
Wrap your code in a try-catch, then you can throw whatever kind of error you like:
try {
/** your code here **/
} catch (Exception $e) {
/** your handling here **/
// i.e.
throw new BadHostNameException($config->m_host);
// or
echo "Could not connect!":
}
Note: you should replace Exception $e with the specific kind of exception a bad host throws so catch(MysqlBadHostnameException $e) (the type of error will be in your error log from your previous attempts or you can do get_class($e) in my example above.
// Isusing a custom exception: Add this outside of your class..
class BadHostNameException extends Exception {}

Global php PDO handling errors

I use try/catch block in my classes methods, If a get an exception, I log the error. But I would like to tell the "User" that a database query/etc failed - and the problem should be fixed soon.
I could use a die() on the Exception in my methods, but that wouldn't be DRY, as I would have to retype it a lot, so any suggestions on how I can do this.
Example method:
public function login($username, $password) {
try {
$this->STH = $this->DBH->prepare("SELECT id, baned, activated FROM users WHERE username = ? AND password = ?");
$this->STH->setFetchMode(PDO::FETCH_OBJ);
$this->STH->execute(array($username, $password));
if (($row = $this->STH->fetch()) !== false)
return $row;
} catch (PDOException $e) {
//Log $e->getMessage();
die('A database error occoured, we are working on the problem, and it should work in a few...');
}
}
If you need a quick fix, you can set a global exception handler, like this:
function pdo_exception_handler($exception) {
if ($exception instanceof PDOException) {
// do something specific for PDO exceptions
} else {
// since the normal exception handler won't be called anymore, you
// should handle normal exceptions yourself too
}
}
set_exception_handler('pdo_exception_handler');
It's OK to repeat yourself in this case because as each instance of die() passes a unique message.

Categories