I am developing an PHP API REST using Value Objects.
I have some value objects as like: ID, Date, Name, etc. When they fail in their construction due to a invalid format or something it throws a InvalidArgumentException.
How can I "collect" all the Exceptions and when the script stops send them in an "error" array in the json response?
The problem is that i think that make hundred of try catch for each value object is not the best way, and I can not find the way to catch multiple exceptions in a try block.
Value Object that may throw an InvalidArgumentException
$authorID = new ID('dd'); // Must be an integer greather than 0 or null
Also I want to pass this ValueObject in the constructor of a Entity
new Insertable($authorID);
If i have multiple ValueObjects that may throw Exceptions, how can I catch them all and make a response with these exceptions as "error" array?
Thanks!
This is not especially elegant, but a possible solution. Just create a global $errors array and collect all messages.
$errors = [];
try {
$authorID = new ID('dd');
} catch(Exception $e) {
$errors[] = $e->getMessage();
}
// and collect some more
try {
$authorID = new ID('ff');
} catch(Exception $e) {
$errors[] = $e->getMessage();
}
At the end output them all
echo json_encode(['errors' => $errors], JSON_PRETTY_PRINT);
will give something like
{
"errors": [
"Author ID needs to be numeric",
"Author ID needs to be numeric"
]
}
We only need to use a single try-catch block as it can handle multiple error(s)/exception(s) in a single go. Example:
try {
$x = 5;
//Statement 1
throw_if(x===5, new Exception('Some Message'));
//Statement 2
throw_if(x===2, new Exception('Some Message'));
//go ahead with your logic
} catch(Exception $e) {
$message = $e->getMessage();
//send error response here
}
If you want to collect all the error(s)/exception(s) and return them all in error response then do so. Example:
$errors = [];
try {
$x = 5;
//Statement 1
if($x===5) {
$errors['stmt1'] = 'Some Message';
}
//Statement 2
if($x===2) {
$errors['stmt2'] = 'Some Message';
}
if(count($errors) > 0) {
//return the $errors here as it contains all error(S)/exception(s)
}
//go ahead with your logic
} catch(Exception $e) {
$message = $e->getMessage();
//Any unknown error/exception will be catches here
}
We have a Google My business account that manage multiple locations. I want to create an interface for answering questions. My problem is that I can't find how to retreive the Author object for the current location.
I tried creating a new Google_Service_MyBusiness_Author object and submitting it but it doesn't seems to work. I'm using MyBusiness API 4.5
$author = new Google_Service_MyBusiness_Author();
$author->setDisplayName('location display name');
$author->setProfilePhotoUrl('someurl.jpg');
$author->setType('MERCHANT');
$answer = new Google_Service_MyBusiness_Answer();
$answer->setText($_POST['answerReplyText']);
$answer->setAuthor($author);
$postBody = new Google_Service_MyBusiness_UpsertAnswerRequest();
$postBody->setAnswer($answer);
try {
$mybusinessService->accounts_locations_questions_answers->upsert($_POST['question_name'],$postBody);
}
catch(Exception $e) {
var_dump($e);
}
I get the 'Request contains an invalid argument' exception. I am doing this the right way ? What should I do to make my answer valid ?
Please try the following by removing the output only fields:
// $author = new Google_Service_MyBusiness_Author();
// $author->setDisplayName('location display name');
// $author->setProfilePhotoUrl('someurl.jpg');
// $author->setType('MERCHANT');
$answer = new Google_Service_MyBusiness_Answer();
$answer->setText($_POST['answerReplyText']);
// $answer->setAuthor($author);
$postBody = new Google_Service_MyBusiness_UpsertAnswerRequest();
$postBody->setAnswer($answer);
try {
$mybusinessService->accounts_locations_questions_answers->upsert($_POST['question_name'],$postBody);
}
catch(Exception $e) {
var_dump($e);
}
This works for me quite well. Hope this will help you too.
I've use Larvel 5.0 with Database transaction all the method in my previous web application it work as well and we are really love it because this application help me much more than our estimated
so we have create another webs application by using this newest version of this framework and used the same Database structure but finaly it would not work for me and another one to.
I have as more peoples and post on some toturial website for asking any belp but not yet get any solution so I record this video for sure about this case.
Issue: My issue I've disabled (//commit()) method all data still can insert into Database.
final function Add()
{
if ($this->request->isMethod('post')) {
//No you will see this method use with Try Catch and testing again
//DB::beginTransaction(); // Ihave testing with outside of try and inside again
Try{
DB::beginTransaction();
$cats = new Cat();
$catD = new CategoryDescriptions();
$cats->parent_id = $this->request->input('category_id');
$cats->status = ($this->request->input('status')) ? $this->request->input('status') : 0;
if (($res['result'] = $cats->save())== true) {
$catD->category_id = $cats->id;
$catD->language_id = 1;
$catD->name = $this->request->input('en_name');
if (($res['result'] = $catD->save()) === true) {
$catD2 = new CategoryDescriptions();
$catD2->category_id = $cats->id;
$catD2->language_id = 2;
$catD2->name = $this->request->input('kh_name');
$res['result'] = $catD2->save();
}
}
if(!empty($res)) {
//DB::commit();
}
return [$res,($res['result'] = $catD->save())];
}catch(\Exception $e){ // I have already try to use Exception $e without backslash
DB::rollback();
}
}
$cat = Cat::with(['CategoryDescriptions', 'children'])->where('status', 1)->get();
return view('admin.categories.add', ['cat' => $cat]);
}
You can check on my video to see that .
Check on my video
I don't know why your code did not work. But you can try with this code I think it's will work. Laravel transaction documentation
try{
DB::transaction(function)use(/*your variables*/){
// your code
});
}catch(\PDOException $exception){
//debug
}
If any exception occurs it will automatically rollback. If you want manual rollback then inside transaction you can throw a manual exception based on your logic.
I'm writing a web application (PHP) for my friend and have decided to use my limited OOP training from Java.
My question is what is the best way to note in my class/application that specific critical things failed without actually breaking my page.
My problem is I have an Object "SummerCamper" which takes a camper_id as it's argument to load all of the necessary data into the object from the database. Say someone specifies a camper_id in the query string that does not exist, I pass it to my objects constructor and the load fails. I don't currently see a way for me to just return false from the constructor.
I have read I could possibly do this with Exceptions, throwing an exception if no records are found in the database or if some sort of validation fails on input of the camper_id from the application etc.
However, I have not really found a great way to alert my program that the Object Load has failed. I tried returning false from within the CATCH but the Object still persists in my php page. I do understand I could put a variable $is_valid = false if the load fails and then check the Object using a get method but I think there may be better ways.
What is the best way of achieving the essential termination of an object if a load fails? Should I load data into the object from outside the constructor? Is there some sort of design pattern that I should look into?
Any help would be appreciated.
function __construct($camper_id){
try{
$query = "SELECT * FROM campers WHERE camper_id = $camper_id";
$getResults = mysql_query($query);
$records = mysql_num_rows($getResults);
if ($records != 1) {
throw new Exception('Camper ID not Found.');
}
while($row = mysql_fetch_array($getResults))
{
$this->camper_id = $row['camper_id'];
$this->first_name = $row['first_name'];
$this->last_name = $row['last_name'];
$this->grade = $row['grade'];
$this->camper_age = $row['camper_age'];
$this->camper_gender = $row['gender'];
$this->return_camper = $row['return_camper'];
}
}
catch(Exception $e){
return false;
}
}
A constructor in PHP will always return void. This
public function __construct()
{
return FALSE;
}
will not work. Throwing an Exception in the constructor
public function __construct($camperId)
{
if($camperId === 1) {
throw new Exception('ID 1 is not in database');
}
}
would terminate script execution unless you catch it somewhere
try {
$camper = new SummerCamper(1);
} catch(Exception $e) {
$camper = FALSE;
}
You could move the above code into a static method of SummerCamper to create instances of it instead of using the new keyword (which is common in Java I heard)
class SummerCamper
{
protected function __construct($camperId)
{
if($camperId === 1) {
throw new Exception('ID 1 is not in database');
}
}
public static function create($camperId)
{
$camper = FALSE;
try {
$camper = new self($camperId);
} catch(Exception $e) {
// uncomment if you want PHP to raise a Notice about it
// trigger_error($e->getMessage(), E_USER_NOTICE);
}
return $camper;
}
}
This way you could do
$camper = SummerCamper::create(1);
and get FALSE in $camper when the $camper_id does not exist. Since statics are considered harmful, you might want to use a Factory instead.
Another option would be to decouple the database access from the SummerCamper altogether. Basically, SummerCamper is an Entity that should only be concerned about SummerCamper things. If you give it knowledge how to persist itself, you are effectively creating an ActiveRecord or RowDataGateway. You could go with a DataMapper approach:
class SummerCamperMapper
{
public function findById($id)
{
$camper = FALSE;
$data = $this->dbAdapter->query('SELECT id, name FROM campers where ?', $id);
if($data) {
$camper = new SummerCamper($data);
}
return $camper;
}
}
and your Entity
class SummerCamper
{
protected $id;
public function __construct(array $data)
{
$this->id = data['id'];
// other assignments
}
}
DataMapper is somewhat more complicated but it gives you decoupled code which is more maintainable and flexible in the end. Have a look around SO, there is a number of questions on these topics.
To add to the others' answers, keep in mind that you can throw different types of exceptions from a single method and handle them each differently:
try {
$camper = new SummerCamper($camper_id);
} catch (NoRecordsException $e) {
// handle no records
} catch (InvalidDataException $e) {
// handle invalid data
}
Throwing an exception from the constructor is probably the right approach. You can catch this in an appropriate place, and take the necessary action (e.g. display an error page). Since you didn't show any code, it's not clear where you were catching your exception or why that didn't seem to work.
try {
$camper = new SummerCamper($id);
$camper->display();
} catch (NonexistentCamper $ex) {
handleFailure($ex);
}
I have a page on my website (high traffic) that does an insert on every page load.
I am curious of the fastest and safest way to (catch an error) and continue if the system is not able to do the insert into MySQL. Should I use try/catch or die or something else. I want to make sure the insert happens but if for some reason it can't I want the page to continue to load anyway.
...
$db = mysql_select_db('mobile', $conn);
mysql_query("INSERT INTO redirects SET ua_string = '$ua_string'") or die('Error #10');
mysql_close($conn);
...
Checking the documentation shows that its returns false on an error. So use the return status rather than or die(). It will return false if it fails, which you can log (or whatever you want to do) and then continue.
$rv = mysql_query("INSERT INTO redirects SET ua_string = '$ua_string'");
if ( $rv === false ){
//handle the error here
}
//page continues loading
This can do the trick,
function createLog($data){
$file = "Your path/incompletejobs.txt";
$fh = fopen($file, 'a') or die("can't open file");
fwrite($fh,$data);
fclose($fh);
}
$qry="INSERT INTO redirects SET ua_string = '$ua_string'"
$result=mysql_query($qry);
if(!$result){
createLog(mysql_error());
}
You can implement throwing exceptions on mysql query fail on your own. What you need is to write a wrapper for mysql_query function, e.g.:
// user defined. corresponding MySQL errno for duplicate key entry
const MYSQL_DUPLICATE_KEY_ENTRY = 1022;
// user defined MySQL exceptions
class MySQLException extends Exception {}
class MySQLDuplicateKeyException extends MySQLException {}
function my_mysql_query($query, $conn=false) {
$res = mysql_query($query, $conn);
if (!$res) {
$errno = mysql_errno($conn);
$error = mysql_error($conn);
switch ($errno) {
case MYSQL_DUPLICATE_KEY_ENTRY:
throw new MySQLDuplicateKeyException($error, $errno);
break;
default:
throw MySQLException($error, $errno);
break;
}
}
// ...
// doing something
// ...
if ($something_is_wrong) {
throw new Exception("Logic exception while performing query result processing");
}
}
try {
mysql_query("INSERT INTO redirects SET ua_string = '$ua_string'")
}
catch (MySQLDuplicateKeyException $e) {
// duplicate entry exception
$e->getMessage();
}
catch (MySQLException $e) {
// other mysql exception (not duplicate key entry)
$e->getMessage();
}
catch (Exception $e) {
// not a MySQL exception
$e->getMessage();
}
if you want to log the error etc you should use try/catch, if you dont; just put # before mysql_query
edit :
you can use try catch like this; so you can log the error and let the page continue to load
function throw_ex($er){
throw new Exception($er);
}
try {
mysql_connect(localhost,'user','pass');
mysql_select_db('test');
$q = mysql_query('select * from asdasda') or throw_ex(mysql_error());
}
catch(exception $e) {
echo "ex: ".$e;
}
Elaborating on yasaluyari's answer I would stick with something like this:
We can just modify our mysql_query as follows:
function mysql_catchquery($query,$emsg='Error submitting the query'){
if ($result=mysql_query($query)) return $result;
else throw new Exception($emsg);
}
Now we can simply use it like this, some good example:
try {
mysql_catchquery('CREATE TEMPORARY TABLE a (ID int(6))');
mysql_catchquery('insert into a values(666),(418),(93)');
mysql_catchquery('insert into b(ID, name) select a.ID, c.name from a join c on a.ID=c.ID');
$result=mysql_catchquery('select * from d where ID=7777777');
while ($tmp=mysql_fetch_assoc($result)) { ... }
} catch (Exception $e) {
echo $e->getMessage();
}
Note how beautiful it is. Whenever any of the qq fails we gtfo with our errors. And you can also note that we don't need now to store the state of the writing queries into a $result variable for verification, because our function now handles it by itself. And the same way it handles the selects, it just assigns the result to a variable as does the normal function, yet handles the errors within itself.
Also note, we don't need to show the actual errors since they bear huge security risk, especially so with this outdated extension. That is why our default will be just fine most of the time. Yet, if we do want to notify the user for some particular query error, we can always pass the second parameter to display our custom error message.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
I am not sure if there is a mysql version of this but adding this line of code allows throwing mysqli_sql_exception.
I know, passed a lot of time and the question is already checked answered but I got a different answer and it may be helpful.
$sql = "INSERT INTO customer(FIELDS)VALUES(VALUES)";
mysql_query($sql);
if (mysql_errno())
{
echo "<script>alert('License already registered');location.replace('customerform.html');</script>";
}
To catch specific error in Mysqli
$conn = ...;
$q = "INSERT INTO redirects (ua_string) VALUES ('$ua_string')";
if (mysqli_query($conn, $q)) {
// Successful
}
else {
die('Mysqli Error: '.$conn->error); // Show Error Complete Description
}
mysqli_close($conn);
Use any method described in the previous post to somehow catch the mysql error.
Most common is:
$res = mysql_query('bla');
if ($res===false) {
//error
die();
}
//normal page
This would also work:
function error() {
//error
die()
}
$res = mysql_query('bla') or error();
//normal page
try { ... } catch {Exception $e) { .... } will not work!
Note: Not directly related to you question but I think it would much more better if you display something usefull to the user. I would never revisit a website that just displays a blank screen or any mysterious error message.
$new_user = new User($user);
$mapper = $this->spot->mapper("App\User");
try{
$id = $mapper->save($new_user);
}catch(Exception $exception){
$data["error"] = true;
$data["message"] = "Error while insertion. Erron in the query";
$data["data"] = $exception->getMessage();
return $response->withStatus(409)
->withHeader("Content-Type", "application/json")
->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
}
if error occurs, you will get something like this->
{
"error": true,
"message": "Error while insertion. Erron in the query",
"data": "An exception occurred while executing 'INSERT INTO \"user\" (...) VALUES (...)' with params [...]:\n\nSQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for integer: \"default\"" }
with status code:409.