I have a PHP platform where user write mongodb query like picture below
and following code print result as a table
$m = new MongoClient();
$db = $m->Forensic;
$coll= $db->mobile_data;
if (isset($_POST['txt_area']) && !empty($_POST['txt_area'])) {
$d = ($_POST['txt_area']);
$p = json_decode($d);
$user_code = $coll->find($p);
When I type correct code system able to ouput all my result but if I write query wrong I am getting error message like
Warning: MongoCollection::find(): expects parameter 1 to be an array or object, null given in C:\xampp\htdocs\reports5.php on line 126
to catch that error i have tried following try catch code but no luck
try {
if (isset($_POST['txt_area']) && !empty($_POST['txt_area'])) {
$d = ($_POST['txt_area']);
$p = json_decode($d);
$user_code = $coll->find($p);
$NumberOfRow2 = $user_code->count();
$user_code->sort(array('Chat_group' => -1, 'Instant_Message' => 1 ));
}
}
catch (MongoCursorException $e) {
echo "error message: ".$e->getMessage()."\n";
echo "error code: ".$e->getCode()."\n";
}
catch (MongoException $e)
{
echo $e->getMessage();
}
catch(MongoResultException $e) {
echo $e->getMessage(), "\n";
$res = $e->getDocument();
var_dump($res);
}
what would be the best way to catch above error
The warning you're seeing is PHP complaining that $coll->find($p); expects $p to be either array or object while it's null. Quoting json_decode documentation:
NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
So a proper way to defend against warning would be:
$p = json_decode($d);
if ($p === null) {
echo "Provided query is invalid!";
} else {
// do your logic
}
Related
I am trying to get all infos from an API, where I dont know every single ID the API can get me. So basically I am calling for 1 info after another while I increase the ID:
<?php
$i = 0;
while ($i < 1000)
{
if ($api->traits()->get($i) == "Uncaught no such id")
{
echo "do something";
$i++;
}
else
{
echo "do something else";
$i++;
}
}
My error code:
Fatal error: Uncaught no such id (status: 404; url:....)
Is there a way that the program doesn't stop on a Fatal error? Or that it reboot the script on fatal error with one higher ID?
I believe you're seeing an Uncaught Exception. See the catch block? That's what it means by "uncaught".
Try this:
<?php
$i = 0;
while ($i < 1000)
{
try
{
$trait = $api->traits()->get($i);
}
catch (Exception $ex)
{
echo "Error: " . $ex->getMessage();
echo "(do something else)";
$i++;
continue;
}
echo "found trait " . $trait;
$i++;
}
Also, this is probably a situation where you should use a for loop instead of a while loop.
<?php
for ($i = 0; $i < 1000; $i++)
{
try
{
$trait = $api->traits()->get($i);
}
catch (Exception $ex)
{
echo "Error: " . $ex->getMessage();
echo "(do something else)";
continue;
}
echo "found trait " . $trait;
}
I should also add that Exception is the very base type or class of exception, and APIs and libraries will typically throw a more specific type of exception.
catch (Exception $ex) { ... }
will catch any type of exception, but
catch (HttpConnectionException $ex) { ... }
would only catch an Exception of type HttpConnectionException. This allows you to handle specific types of errors differently. You can use get_class($ex) to see what exact type of Exception the API is throwing if you like.
i have been working on some application which involves the cURL operation and then Scraping the content of particular URLs.
And there are few computation/calculations following the Scraping.
The issue which i'm facing right now is related to UNDEFINED ARRAY INDEX.
Here are few functions facing like issues:
{Notice: Undefined offset: 0 in D:\xampp\htdocs\Alps-Phase2\alps\include\alpsOP\scrap-process-request2.php on line 263}
there are more functions similar to these:
function getDomainName($objScrap)
{
try
{
$result = $objScrap->getDomainName();
return $result; //Notice: Undefined offset: 0
}
catch( Exception $e)
{
echo "Error in getDomainName !";
return FALSE;
}
}
function getDataForDomainName($objScrap)
{
try
{
$result = $objScrap->checkForKeywordInDomain();
return $result[0]; // Notice: Undefined offset: 0
}
catch( Exception $e)
{
echo "Error in getDataForDomainName !";
return FALSE;
}
}
function getDensityForDomainName($objScrap){
try
{
$result = $objScrap->getDomainDensity();
return $result[0]; // Notice: Undefined offset: 0
}
catch( Exception $e)
{
echo "Error in getDensityForDomainName !";
return FALSE;
}
}
The function definitions for some calls:
function getDomainDensity()
{
$result=$this->getDomainName();
return $this->getKeywordDensity($result);
}
function getDomainName()
{
preg_match($this->_regExpDomain,$this->_url,$match);
if($match != NULL)
return $match[2];
else
return array(
0=> 'Please check URL '.$this->$_url.' [Domain Name]',
'error' => 'Please check URL '.$this->$_url.' [Domain Name]'
);
}
function getKeywordDensity(&$subject)
{
$splitKeywordCountTotal_len=0;
$splitKeywordCount = array();
$resultArray = array();
for($count_i=0;$count_i<count($this->_keywords);$count_i++)
{
$splitKeyword = $this->splitKeyword($this->_keywords[$count_i]);
$splitKeywordCount=0;
$splitKeywordCount = $this->prepareResultArray($subject,NULL,$splitKeyword);
$matchedKeywordCharacterCount=0;
$f=0;
foreach ($splitKeywordCount as $val=>$key)
{
$splitKeywordCount[$f][2]=strlen($key[0]);
$splitKeywordCount[$f][3]=$key[1]*strlen($key[0]);
$matchedKeywordCharacterCount=$matchedKeywordCharacterCount+$splitKeywordCount[$f][3];
$f++;
}
$totalWordsInVisibleContent = $this->getNumberOfWordsInSubject($subject);
$f=0;
$totalWordsInVisibleContent_len=0;
foreach ($totalWordsInVisibleContent as $val=>$key)
{
$totalWordsInVisibleContent_len=$totalWordsInVisibleContent_len+strlen($key);
}
$splitKeywordCountTotal = 0;
for($count_j=0;$count_j < count($splitKeywordCount);$count_j++)
{
$splitKeywordCountTotal = $splitKeywordCountTotal + $splitKeywordCount[$count_j][1];
$splitKeywordCountTotal_len = $splitKeywordCountTotal_len + $splitKeywordCount[$count_j][2];
}
$resultArray[$count_i] = array();
$resultArray[$count_i][0] = $this->_keywords[$count_i];
$resultArray[$count_i][1] = $matchedKeywordCharacterCount/ ($totalWordsInVisibleContent_len);
$resultArray[$count_i][2] = $splitKeywordCountTotal;
$resultArray[$count_i][3] = $matchedKeywordCharacterCount;
$resultArray[$count_i][4] = $totalWordsInVisibleContent;
$resultArray[$count_i][5] = $splitKeywordCountTotal_len;
$resultArray[$count_i][6] = $totalWordsInVisibleContent_len;
}
return $resultArray;
}
moreover, i plan to run half a million URLs for the same application. If these NOTICES keep on showing up, my application would be facing poor performance.
So guys, need help in resolving the issue.
** sorry for the drafting of code... new to the forum , dint know how to use the constructs.. :(
Turn Off Html errors
include the following on the top
error_reporting(E_ALL);
ini_set('display_errors', 'On');
ini_set('html_errors', 'Off');
I have faced such an issue just today! I use PHP7.3.5 and I get the same error, for searching around I found the solution to be:
Instead of:
try
{
$result = $objScrap->checkForKeywordInDomain();
return $result[0]; // Notice: Undefined offset: 0
}
Change to:
try
{
$result = $objScrap->checkForKeywordInDomain();
if(isset($result[0])){
return $result[0];
}
}
hope this can help anyone }else{ :).
I have some script, that calls an error: Fatal error: Call to a member function GetData() on a non-object in .... I'm trying to catch this error, but it doesn't work, watch my code below:
try {
if ($data = $m->users()->GetData()) {
print_r( $data );
}
}
catch (Exception $e) {
echo 'Hey, it is an error man!';
}
How to catch it? Turning off all errors in php is impossible. I mean that sometimes I really need this error.
upd 1. Well, solution is simple:
if (is_object($m->users()) && ($data = $m->users()->GetData())) {
print_r( $data );
} else {
echo 'Hey, it is an error man!';
Thank you all!
In PHP errors and exceptions are from different separated worlds. Look more
PHP: exceptions vs errors?
You can check returned object before call method GetData()
try {
if (is_object($m->users()) && ($data = $m->users()->GetData())) {
print_r( $data );
}
} catch (Exception $e) {
echo 'Hey, it's an error man!';
}
use following to avoid your error and you should used shutdown error handler.
try {
$obj = $m->users();
if ($data =$obj->GetData()) {
print_r( $data );
}
}
catch (Exception $e) {
echo 'Hey, it's an error man!';
}
//shut down error handler
function shutdownErrorHandler() {
$error = error_get_last();
if ($error !== NULL) {
echo "Error: [SHUTDOWN] error type: " . $error['type'] . " | error file: " . $error['file'] . " | line: " . $error['line'] . " | error message: " . $error['message'] . PHP_EOL;
} else {
echo "Normal shutdown or user aborted";
}
}
register_shutdown_function('shutdownErrorHandler');
Fatal Errors are not the same as Exceptions, and they are not usually recoverable. What they are, however, is usually avoidable, and sometimes they are "catchable" via PHP5's set_error_handler function.
Best practice, however, is to simply do the work of checking for valid objects before trying to call methods on them.
I'm using PhpExcel for my app and see a error. I've tried handling exception with
try{}catch(){} but it doesn't work. How to handle exception with PhpExcel? Here is my code:
function import($excelObj) {
$sheet=$excelObj->getActiveSheet();
$cell = $sheet->getCellByColumnAndRow(1, 10);//assume we need calculate at col 1, row 10
try {
//This line seen error, but cannot echo in catch.
$val = $cell->getCalculatedValue(); // $cell contain a formula, example: `=A1+A6-A8`
// with A1 is constant, A6 is formula `=A2*A5`
// and A8 is another `=A1/(A4*100)-A7`
return $val;
} catch (Exception $e) {
echo $e->getTraceAsTring();
}
}
Thank for helps!
The calculation engine should throw a normal PHP exception that is catcheable. The front-end logic that I use for debugging calculation engine errors is:
// enable debugging
PHPExcel_Calculation::getInstance()->writeDebugLog = true;
$formulaValue = $sheet->getCell($cell)->getValue();
echo '<b>'.$cell.' Value is </b>'.$formulaValue."<br />\n";
$calculate = false;
try {
$tokens = PHPExcel_Calculation::getInstance()->parseFormula($formulaValue,$sheet->getCell($cell));
echo '<b>Parser Stack :-</b><pre>';
print_r($tokens);
echo '</pre>';
$calculate = true;
} catch (Exception $e) {
echo "PARSER ERROR: ".$e->getMessage()."<br />\n";
echo '<b>Parser Stack :-</b><pre>';
print_r($tokens);
echo '</pre>';
}
if ($calculate) {
// calculate
try {
$cellValue = $sheet->getCell($cell)->getCalculatedValue();
} catch (Exception $e) {
echo "CALCULATION ENGINE ERROR: ".$e->getMessage()."<br />\n";
echo '<h3>Evaluation Log:</h3><pre>';
print_r(PHPExcel_Calculation::getInstance()->debugLog);
echo '</pre>';
}
}
This gives a lot of additional information about how the calculation engine works, that can be extremely useful when debugging.
I want to catch this error:
$a[1] = 'jfksjfks';
try {
$b = $a[0];
} catch (\Exception $e) {
echo "jsdlkjflsjfkjl";
}
Edit: in fact, I got this error on the following line:
$parse = $xml->children[0]->children[0]->toArray();
You need to define your custom error handler like:
<?php
set_error_handler('exceptions_error_handler');
function exceptions_error_handler($severity, $message, $filename, $lineno) {
if (error_reporting() == 0) {
return;
}
if (error_reporting() & $severity) {
throw new ErrorException($message, 0, $severity, $filename, $lineno);
}
}
$a[1] = 'jfksjfks';
try {
$b = $a[0];
} catch (Exception $e) {
echo "jsdlkjflsjfkjl";
}
You can't with a try/catch block, as this is an error, not an exception.
Always tries offsets before using them:
if( isset( $a[ 0 ] ) { $b = $a[ 0 ]; }
I know it's 2016 but in case someone gets to this post.
You could use the array_key_exists($index, $array) method in order to avoid the exception to happen.
$index = 99999;
$array = [1,2,3,4,5,6];
if(!array_key_exists($index, $array))
{
//Throw myCustomException;
}
$a[1] = 'jfksjfks';
try {
$offset = 0;
if(isset($a[$offset]))
$b = $a[$offset];
else
throw new Exception("Notice: Undefined offset: ".$offset);
} catch (Exception $e) {
echo $e->getMessage();
}
Or, without the inefficiency of creating a very temporary exception:
$a[1] = 'jfksjfks';
$offset = 0;
if(isset($a[$offset]))
$b = $a[$offset];
else
echo "Notice: Undefined offset: ".$offset;
Important: Prefer not using this method, use others. While it works, it is ugly and has its own pitfalls, like falling into the trap of converting real and meaningful output into exceptions.
Normally, you can't catch notices with a simple try-catch block. But there's a hacky and ugly way to do it:
function convert_notice_to_exception($output)
{
if (($noticeStartPoint = \strpos($output, "<b>Notice</b>:")) !== false) {
$position = $noticeStartPoint;
for ($i = 0; $i < 3; $i++)
$position = strpos($output, "</b>", $position) + 1;
$noticeEndPoint = $position;
$noticeLength = $noticeEndPoint + 3 - $noticeStartPoint;
$noticeMessage = \substr($output, $noticeStartPoint, $noticeLength);
throw new \Exception($noticeMessage);
} else
echo $output;
}
try {
ob_start();
// Codes here
$codeOutput = ob_get_clean();
convert_notice_to_exception($codeOutput);
} catch (\Exception $exception) {
}
Also, you can use this function for to catch warnings. Just change function name to convert_warning_to_exception and change "<b>Notice</b>:" to "<b>Warning</b>:".
Note: The function will catch normal output that contains:
<b>Notice</b>:
To escape from this problem, simply, change it to:
<b>Notice:</b>
For the people who are getting the error
PHP Notice: unserialize(): Error at offset 191 of 285 bytes in ...
and are getting the data from a database, Make sure that you have the database set the the correct encoding, I had the database set as latin1_swedish_ci and all of the data looked perfect, Infact when i copied it into a online unserialize it worked fine. I changed the collation to utf8mb4_unicode_ci and all worked fine.
Source User Contributed Notes: https://www.php.net/manual/pt_BR/function.unserialize.php
I tried to utf8_decode before unserialize, and it's works fine.
Im sure why the Error Throw but i fix some..
in html2pdf.class.php
on Lines 2132:
//FIX:
$ctop=$corr[$y][$x][2]<=count($sw)?$corr[$y][$x][2]:count($sw);
$s = 0; for ($i=0; $i<$ctop; $i++) {$s+= array_key_exists($x+$i, $sw)? $sw[$x+$i]:0;}
SAME On line 2138:
//FIX:
$ctop=$corr[$y][$x][2]<=count($sw)?$corr[$y][$x][2]:count($sw);
for ($i=0; $i<$ctop; $i++) {
the problem the array $sw not have a key of $corr[$y][$x][2] so i fix the loop for to max count($sw) to fix ..
I dont know if that create an another consecuense but i resolve my problem y dont have any more errors..
So i hope works to you ..!!!
Beats Reguards