Reputation: 11678
This is my try/catch block in PHP:
try
{
$api = new api($_GET["id"]);
echo $api -> processRequest();
} catch (Exception $e) {
$error = array("error" => $e->getMessage());
echo json_encode($error);
}
When there is nothing in the $_GET["id"]
, I still get the notice error.
How can I avoid getting this error?
Upvotes: 34
Views: 45738
Reputation: 49
Structure of try...catch
<?php
try {
// perform some task
} catch (Exception $ex) {
// jump to this part
// if an exception occurred
}
You Can Use isset
<?php
if(isset($_GET['id'])){
$api = new api($_GET["id"]);
echo $api -> processRequest();
}else{
$error = array("error" => $e->getMessage());
echo json_encode($error);
}
?>
Bonus Example:
<?php
if(isset($_GET['name'])){
$name = $_GET['name'];
}else{
$name = "Name not set in GET Method";
}
if(isset($_GET['age'])){
$name = $_GET['age'];
}else{
$name = "<br>Age not set in GET Method";
}
echo $name;
echo $age;
?>
Upvotes: 0
Reputation: 47
You have to catch Throwable not Exception:
} catch (Throwable $e) {
Upvotes: 3
Reputation: 1086
As of PHP 7, we now have the Null Coalescing Operator.
try
{
$api = new \Api($_GET['id'] ?? null);
}
catch (\Exception $e)
{
$error = ["error" => $e->getMessage()];
return json_encode($error);
}
Upvotes: 0
Reputation: 856
If you want a fast and "dirty" solution, you can use
$api = new api(@$_GET["id"]);
Edit:
Since PHP 7.0 there is a much better and accepted solution: using the null coalescing operator (??). With it you can shorten your code to
$api = new api($_GET["id"] ?? null);
and you don't get a notice because you defined what should happen in the case the variable is not defined.
Upvotes: 4
Reputation: 6896
If the absence of id means nothing should then be processed, then you should be testing for the absence of the id, and managing the failure gracefully.
if(!isset($_GET['id'] || empty($_GET['id']){
// abort early
}
THEN go on and do you try/catch.
Unless of course you were to add some smartness to api() so that is responded with a default id, that you'd declare in the function
function api($id = 1) {}
So, it "all depends", but try and fail early if you can.
Upvotes: 1
Reputation: 8818
Try checking if the $_GET
was set
try
{
if(isset($_GET["id"]))
{
$api = new api($_GET["id"]);
echo $api -> processRequest();
}
} catch (Exception $e) {
$error = array("error" => $e->getMessage());
echo json_encode($error);
}
Upvotes: 0
Reputation: 7475
use isset
function to check if the variable is set or not:
if( isset($_GET['id'])){
$api = new api($_GET["id"]);
echo $api -> processRequest();
}
Upvotes: 31