multiple methods try without skipping others php - php

I have this code:
try{
firstMethod()
secondMethod()
}
catch(Exception $e){
....
}
What I want is execute all try/catch block functions but capturing if one throws exception, without skipping the following methods
a possible but not pretty code would be:
try{
firstMethod();
}
catch(Exception $e){
....
}
try{
secondMethod();
}
catch(Exception $e){
....
}

I am assuming you might have a lot of those if you are looking for more convenient way than "not pretty" take?
I would say just loop through them:
foreach ( [ 'firstMethod', 'secondMethod' ] as $callable ) {
try {
$callable();
}
catch ( Exception $e ) {
}
}

Why not write try catch in each function and log the exceptions somewhere.
function firstMethod() {
try {
//code
}
catch (Exception $e) {
logException($e);
}
}
function secondMethod() {
try {
//code
}
catch (Exception $e) {
logException($e);
}
}
function mainMethod() {
firstMethod();
secondMethod();
}
This will help in doing something like this:
function someOtherMethod() {
secondMethod();
}

Related

Catch Guzzle Exception and return string

So I need some help on building out one of my methods for retrieving twitter lists using IDs. Below, I will describe and go into detail on what it's returning.
Code:
public static function get_list($list_id)
{
$lists = self::get_lists();
$params = [
'list.fields' => 'created_at,follower_count,member_count,private,description,owner_id',
'user.fields' => 'created_at,description,entities,id,location,name,pinned_tweet_id,profile_image_url,protected,public_metrics,url,username,verified,withheld'
];
try {
$list = $lists->get($list_id, $params);
} catch (\GuzzleHttp\Exception\ClientException $e) {
return $e;
}
return $list;
}
When $lists->get() has an issue, it throws the following items object(GuzzleHttp\Exception\ClientException)#1640 (10) { ["request":"GuzzleHttp\Exception\RequestException":private]=> error.
What I'd like to achieve:
Return $e so that I can read the error (Unable to get this to work).
If I switch out return $e for return 'Hello', I still see the object and not the string.
The IDE suggests that it #throws GuzzleException.
Does anyone see anything wrong in how I'm handling my exception and why I'm unable to properly return the exception error?
Try to use exception hierarchy to catch any exception. ClientException only catches status code between 400x-499. To catch other exception or catch within the same Exception you can use RequestException.
public static function get_list($list_id)
{
$lists = self::get_lists();
$params = [
'list.fields' => 'created_at,follower_count,member_count,private,description,owner_id',
'user.fields' => 'created_at,description,entities,id,location,name,pinned_tweet_id,profile_image_url,protected,public_metrics,url,username,verified,withheld'
];
try {
$list = $lists->get($list_id, $params);
if($list->getStatusCode() == 200)){
$return_list = json_decode($list->getBody(),true);
}
} catch (\GuzzleHttp\Exception\ClientException $e) {
$error['error'] = $e->getMessage();
$error['request'] = $e->getRequest();
if($e->hasResponse()){
// you can pass a specific status code to catch a particular error here I have catched 400 Bad Request.
if ($e->getResponse()->getStatusCode() == '400'){
$error['response'] = $e->getResponse();
}
}
return $error;
} catch(\GuzzleHttp\Exception\RequestException $se){
$error['error'] = $e->getMessage();
$error['request'] = $e->getRequest();
return $error;
} catch(Exception $e){
//other errors
}
return $list;
}

Use error outside catch block

Let's work with an example like this:
try {
if( $var == false ) {
throw new Exception('Fail');
}
} catch (Exception $e) {
$error = $e->getMessage();
}
Is there any way i can use $error outside the catch block?
If i try to print it outside,it shows nothing , so i'm sure i'm doing this wrong. Any help would be apreciated.
EDIT: This is my exact situation of the code click
I need to use $error , in another piece of code , outside of the class
Actually you are returning the error message, if you remove the return false statement, and try to print outside the loop it will print.
you can do that in 2 way:
Option1:
try {
if( $var == false ){
throw new Exception('Fail');
}
} catch (Exception $e){
$error = $e->getMessage();
// return false;
}
print_r($error);
Option 2:
try {
if( $var == false ){
throw new Exception('Fail');
}
} catch (Exception $e){
return $error = $e->getMessage();
}
This will return true if no error happens. Else it will return the error.
$error = false;
try {
if( $var == false ){
throw new Exception('Fail');
}
} catch (Exception $e){
$error = $e->getMessage();
}
return $error;
It depends on your implementation whether to return true or false.
You should not
The $error is declard inside the catch.
You your function throws a Exception don't use try cactch. just throw the Exception
Your function should return just one type;
If it returns boolean, return aways boolean
Maybe if you need to print the error, print it inside the catch

issues with php mail function, not receiving email, zen_mail

Reference: https://www.zen-cart.com/showthread.php?64003-zen_mail-How-does-it-work
I have modified a php file in the below lines:
function sub_button() {
$process_button_string = zen_draw_getuserinfo_field('usercasenumber_', $_POST['u_case'])
}
return $process_button_string;
try {
zen_mail("xxxxxx", "xxxxxx#gmail.com","xxxxxxxx", $process_button_string, W_NAME, EMAIL_FROM);
} catch (Exception $e) {
}
}
but still not receiving any email on completing doing submit on that page. everything else goes well. I am not very good with php and just added below part:
try {
zen_mail("xxxxxx", "xxxxxx#gmail.com","xxxxxxxx", $process_button_string, W_NAME, EMAIL_FROM);
} catch (Exception $e) {
}
Am I doing something wrong? Please help
I resolved it! :)
function sub_button() {
$process_button_string = zen_draw_getuserinfo_field('usercasenumber_', $_POST['u_case']);
}
$msg = $_POST['u_case'];
try {
zen_mail("xxxxxx", "xxxxxx#gmail.com","xxxxxxxx",
$msg, W_NAME, EMAIL_FROM);
} catch (Exception $e) {
}
return $process_button_string;
}

mysql 'too long' exception not working in php

public function edit($body){
try
{
$stmt=$this->db->prepare("UPDATE news SET body=:body");
$stmt->bindparam(":body",$body);
$stmt->execute();
return true;
}
catch(PDOException $e)
{
echo $e->getMessage();
return false;
}
}
It always saving missed data when data too long for column 'body' I want to catch exception.

execute statement only if an exception occurs but when multiple catch clauses in place

I need to rollback transaction and send correct response to the client if anything in the try block fails so I do it like that:
try {
$wf = $this->createWordForm($requestParams);
$wfl = $this->createWordFormLink($requestParams, $wf);
$wordList = $this->bindWordFormOrLinkToTextWord($requestParams, $wf, $wfl);
$db->commit();
} catch (Kohana_ORM_Validation_Exception $e) {
$exceptionHasOccured = TRUE;
return JsonResponse::ValidationFail($this->response, $e->errors());
} catch (Exception $e) {
$exceptionHasOccured = TRUE;
return JsonResponse::Error($this->response, $e->getMessage());
} finally {
if ($exceptionHasOccured) {
$db->rollback();
}
}
As you can see I'm using finally construction to rollback transaction. Is this correct approach?
You could catch all exceptions in one catch block, as long as your not specifically using the exception type for any purpose.
try {
$wf = $this->createWordForm($requestParams);
$wfl = $this->createWordFormLink($requestParams, $wf);
$wordList = $this->bindWordFormOrLinkToTextWord($requestParams, $wf, $wfl);
$db->commit();
} catch (Exception $e) {
$db->rollback();
if($e instanceof Kohana_ORM_Validation_Exception ) {
return JsonResponse::ValidationFail($this->response, $e->errors());
} else {
return JsonResponse::Error($this->response, $e->getMessage())
}
}

Categories