I have a list of Instances ID saved in DB.
a periodic check validates those ID's against AWS.
The problem is that if one of the instances doesnt exist then i get Exception and the whole request fails (none of the ID's return).
Is there a way to skip that missing ID and get back all data except for that specific instanceID?
My code:
$requesltArray = ['Filters' => $this->_Filters, 'InstanceIds' => $this->_InstanceIDs];
try {
$reservations = $this->_EC2Client->DescribeInstances($requesltArray)->toArray();
} catch (Ec2Exception $exc) {
echo $exc;
return [];
}
results in Exception:
aws sdk Error executing "DescribeInstances" InvalidInstanceID.NotFound
Depending of the number of instances you have, you might consider then to perform your DescribeInstances request for each individual IDs.
$reservations = [];
foreach($this->_InstanceIDs as $anInstance){
try {
$requesltArray = ['Filters' => $this->_Filters, 'InstanceIds' => $anInstance];
$aReservation = $this->_EC2Client->DescribeInstances($requesltArray)->toArray();
$reservations[] = $aReservation;
} catch (Ec2Exception $exc) {
// --> Delete the instance from your database?
continue;
}
}
dd($reservations);
Related
I'm using Send In Blue to keep track of my contacts. Throughout my site I'm either updating the contact or creating a new one but I've never had to combine the two. I have my pieces of code separately below.
How can I combine the two so that if there's a user there already then it updates them and if not then it creates them?
Is it possible to update first and if that fails create them?
try {
$updateContact = new \SendinBlue\Client\Model\UpdateContact($data);
$result = $SendInBlue->updateContact($email, $updateContact);
return true;
} catch (Exception $e) {
}
And this is the code to create a contact:
try {
$createContact = new \SendinBlue\Client\Model\CreateContact($data);
$result = $SendInBlue->createContact($email, $createContact);
return true;
} catch (Exception $e) {
}
You can remove the updateContact() and just use createContact() because the is an updateEnabled option that can be set during the creation attempt. The purpose of this option is to "Facilitate to update the existing contact in the same request (updateEnabled = true)"
You can either set this while creating the CreateContact object ...
$data["updateEnabled"] = true;
$createContact = new \SendinBlue\Client\Model\CreateContact($data);
Or by using the setUpdateEnabled() method ...
try {
$createContact = new \SendinBlue\Client\Model\CreateContact($data);
$createContact->setUpdateEnabled(true);
$result = $SendInBlue->createContact($email, $createContact);
return true;
} catch (Exception $e) {
}
For reference, here is the code for the CreateContact class that you're using, and here is the documentation for the raw SendInBlue API.
I have a Laravel Job that is being dispatched. The job gets some records to process then calls an API with each. The API could occasionally could throw an error e.g. HTTP500 etc. This library (Goose) uses Guzzle.
I want to catch the error, flag the record to try again later and continue with the rest of the records in the loop.
My code is as follows but when an error occurs, the foreach loop ceases and the job does not continue.
My guess is that the Job Handler in Laravel is throwing a fatal error and the job is being halted at a higher level.
public function extractArticles() {
$articles = $this->fetchArticlesToExtract();
$goose = new GooseClient();
foreach($articles as $article) {
try {
//Get the Article Data - Errors can happen here
$articleData = $goose->extractContent($article->source_url);
//Do Some Processing
$article->save();
}
catch (\Goose\Exception $e) {
//Set a flag to come back later
//Try continue with next record
continue;
}
}
return;
}
How can I tell the Job to continue? There is only a small set of errors that can occur here and I have written the logic to 'try again', so I'm happy to not stop the job completely.
You have too many } and they are in the wrong places
public function extractArticles() {
$articles = $this->fetchArticlesToExtract();
$goose = new GooseClient();
foreach($articles as $article) {
try {
//Get the Article Data - Errors can happen here
$articleData = $goose->extractContent($article->source_url);
//Do Some Processing
$article->save();
}
//} removed
catch (\Goose\Exception $e) {
//Set a flag to come back later
//Try continue with next record
continue;
}
}
return;
}
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 have created a Webservice from a BAPI in SAP to insert some AccountDocuments into SAP. The system in these cases needs a COMMIT-call after a successful insert call. Both of these functions must be called in "one context".
Now I'm facing the problem that I don't know how to do this in php or if there is any way to do this?
I have created the following example, but it doesn't work. The COMMIT function gets executed but it has no impact in SAP. I cannot see the data in the databases, although the first call returns "Data successfully booked". I know that you must confirm this with the COMMIT call in SAP. In SE37 there is a way to put 2 function calls into one Sequence. I'm searching the php-way to do this.
function insertAccntDoc($accntgl, $currAmount, $docHeader, $accntTax)
{
#Define Authentication
$SOAP_AUTH = array( 'login' => SAPUSER,
'password' => SAPPASSWORD);
$WSDL = "url_to_my_wsdl";
#Create Client Object, download and parse WSDL
$client = new SoapClient($WSDL, $SOAP_AUTH);
#Setup input parameters (SAP Likes to Capitalise the parameter names)
$params = array(
'AccountGl' => $accntgl,
'CurrencyAmount' => $currAmount,
'DocumentHeader' => $docHeader,
'AccountTax' => $accntTax
);
#Call Operation (Function). Catch and display any errors
try
{
$result = $client->AcctngDocumentPost($params);
$result = $client->BapiServiceTransactionCommit();
$result->Gebucht = 'Committed';
if(count($result->Return) > 1)
{
$client->BapiServiceTransactionRollback();
$result->Gebucht = 'Rollback';
}
else if($result->Return->item->Type == 'S')
{
try
{
$client->BapiServiceTransactionCommit();
$result->Gebucht = 'Committed';
}
catch(SoapFault $exception)
{
$client->BapiServiceTransactionRollback();
$result->Fehler = "***Caught Exception***<br>".$exception."<br>***END Exception***<br>";
$result->Gebucht = 'Fehler beim Committen';
}
}
}
catch (SoapFault $exception)
{
$client->BapiServiceTransactionRollback();
$result->Fehler = "***Caught Exception***<br>".$exception."<br>***END Exception***<br>";
$result->Gebucht = 'Fehler beim Anlegen';
}
#Output the results
$result->FlexRet = 'insertAccntDoc';
return $result;
}
Thanks!
This link gives details on how to use "stateful" web services. This is required to have a shared session.
http://scn.sap.com/thread/140909
I am using an array to log key information in a foreach statement for use later on, I set the array at the top of the page to ensure that it is available across all functions in the script.
I have tested to see that the array is set, and it seems to work outside a try catch statement see commented code below.
$completeClients = array();
if($can_synchronise === true)
{
$success = sync_to_client($package, $client);
try
{
if($success)
{
$completeClients[] = "Sync to ".$client->getName()." has completed";
}
else
{
$completeClients[] = "Sync to ".$client->getName()." has failed";
}
}
catch(Exception $ex)
{
logMsg("Unable to save client data reason: ". $ex->getMessage(), STATUS_ERROR , $client->getAddress());
}
exit( EXIT_OK );//Exit the child process
}
}
else
{
**// The array is set correctly when called here**
$completeClients[] = "Sync to ".$client->getName()." has failed";
}
I have printed the array and when it is called in the try catch statement it looks like:
Array
(
[0] => Sync to TPSDEV_PHILIPS_TWO has completed
)
Array
(
[0] => Sync to TPSDEV_TC_Client2 has completed
)
Array
(
)
It should look like
Array
(
[0] => Sync to TPSDEV_PHILIPS_TWO has completed
)
Array
(
[0] => Sync to TPSDEV_PHILIPS_TWO has completed
[1] => Sync to TPSDEV_TC_Client2 has completed
)
Array
(
[0] => Sync to TPSDEV_PHILIPS_TWO has completed
[1] => Sync to TPSDEV_TC_Client2 has completed
)
Do you guys have any idea? im stumped.
This doesn't add up:
exit( EXIT_OK );
It's outside of the try-catch block, so whatever happens (succesful or otherwise), after inserting the first value in the array, you're exiting the script. As soon as the branch if ($can_synchronise === true) gets executed once.
What's more, there's no loop to be seen anywhere, so how do you expect this to produce an array that contains more than 1 value?
There's something else, too: you're calling the sync_to_client outside of the try-catch block, which only contains an if-else and an assignment to an array. Nothing that might throw an exception AFAIK, unless $client->getName() throws, but the name implies a getter, which is unlikely to throw in the first place.
You probably want to call the sync_to_client in the try-catch, if that's the function that is likely to throw an exception.
Lastly, if this is part of a loop of some sort, and you've posted just the inner code, then you really ought to move this:
$completeClients = array();
out of the loop, because now, each time this block of code gets executed, you're reassigning $completeClients to hold a new, empty array.
Assuming an array of client objects, your code should look something like this:
$completeClients = array();
foreach($clients as $client)
{
if (!$canSynchronize)
{
$completeClients[] = 'Sync to '.$client->getName().' has failed';
continue;//messy, best wrap the try-catch in an else branch
}
try
{
if (sync_to_client($package, $client))
{
$completeClients[] = 'Sync to '.$client->getName().' has completed';
}
else
{
$completeClients[] = 'Sync to '.$client->getName().' has failed';
}
}
catch(Exception $e)
{
logMsg("Unable to save client data reason: ". $ex->getMessage(), STATUS_ERROR , $client->getAddress());
//$completeClients[] = 'Unable to Sync: '.$e->getMessage();
//exit( EXIT_OK);
throw $e;//rethrow, is what I'd do.
}
}
However, what this code effectively does is catch exceptions, and sort-of hush them up. If something fails, there's likely to be a bug in your code. Don't catch an exception unless you know how to deal with it. And don't catch everything.
PDO throws PDOException instances. SOAP clients throw SoapFault's, my objects throw either InvalidArgumentException, RuntimeException or BadMethodCallException instances. There are many types, each one of them signals a specific type of problem. Don't try to be yoda, playing pokemon
I don't know if mentioned code placed inside an array or function, however I think if you replace following with something else it can help
$completeClients = array();
with
if (!isset($completeClients)) {
$completeClients = array();
}