I would like to delete other relations even if any of the previous deletions fail. I have used a lot of try/catch to achieve this. Is there a way I can reduce the amount of try-catch in my code or do it without try-catch?
public function delete_live_event(Request $request){
try{
$user = User::find($request->auth_user_id);
if(!$request->journey_item_id){
return response()->json(['StatusMessage' => 'Bir hata oluştu !', 'StatusCode' => 401,'error'=>'live_event_id gönderilmedi'], 401);
}
$journey_item = JourneyItem::find($request->journey_item_id);
if ($journey_item == null) {
return response()->json(['StatusMessage' => __('contents.not_found'), 'StatusCode' => 404], 404);
}
/** Assigned Users deleted **/
try{
UserJourney::where('as_journey_id',$journey_item->journey->id)->delete();
}catch (\Exception $e){ //log
}
/** journey deleted **/
try{
$journey_item->journey()->delete();
}catch (\Exception $e){
//Log
}
/** content deleted **/
try{
$journey_item->content()->delete();
}catch (\Exception $e){//Log
}
/** notifications deleted **/
try{
UserJourneyItemNotification::where('as_journey_item_id', $journey_item->id)->delete();
}catch (\Exception $e){//Log
}
/** item deleted **/
try{
$journey_item->item()->delete();
}catch (\Exception $e){//Log
}
/** journey_item deleted **/
$journey_item->delete();
return response()->json(['StatusMessage' => 'Live event is deleted succesfuly', 'StatusCode' => 200], 200);
}catch (\Exception $e){
//TODO error log
return response()->json(['StatusMessage' => 'Bir hata oluştu !', 'StatusCode' => 400], 401);
}
}
Try / Catch is usually used in a situation where you want to catch an error in order to stop further processing. If the each of the items in your list can be deleted, even if the others cannot be deleted, then there is no reason to use try/catch at all.
You also do not need to wrap your main function in try/catch block, as the only failure that would occur within that code is if you called a method that did not exist in your object. That would be a code failure, which would require correction. This is not the type of error that you would want to allow processing to continue, as the missing method is a code bug and should be corrected.
Related
I have an ionic app that makes a request to my laravel server to make the payment on the stripe platform.
but causing the error returns the Handler.php error and I cannot access the object.
How do I get the "Your card has insufficient funds." in a json?
to later show it in my app.
I already tried the try and catch and keep sending the error in handle
image
My controller:
try {
//Charge the Card
$charge = $stripe->charges()->create([
'source' => $request->token,
'currency' => $reservation->divisa_code,
'amount' => $reservation->total_price_divisa,
'description' => "App Payment Booking Seadust Cancun",
'receipt_email' => $guest->email
]);
} catch (\Stripe\Error\InvalidRequest $e) {
//Send User to Error Page
return $e;
} catch(\Stripe\Error\Card $e) {
// Since it's a decline, \Stripe\Error\Card will be caught
$body = $e->getJsonBody();
return $body;
} catch (\Stripe\Error\Base $e) {
//Send User to Error Page
return $e;
} catch (Exception $e) {
return $e;
};
I think you are catching the wrong exception (check here), you probably should have something like this:
try {
//Charge the Card
$charge = $stripe->charges()->create([
'source' => $request->token,
'currency' => $reservation->divisa_code,
'amount' => $reservation->total_price_divisa,
'description' => "App Payment Booking Seadust Cancun",
'receipt_email' => $guest->email
]);
} catch (\Stripe\Error\InvalidRequest $e) {
//Send User to Error Page
return $e;
} catch (Cartalyst\Stripe\Exception\CardErrorException $e) {
return $e->getMessage();
// or if you want a "bad response" in case of exception
// abort(404, $e->getMessage());
} catch (Exception $e) {
return $e;
};
i am sending otp using twilio,laravel, message is working now, but i want to set exception for if message is not delivered etc i have tried like
public function send_otp()
{
try {
$account_sid = env('TWILIO_ACCOUNT_SID');
$auth_token = env('TWILIO_AUTH_TOKEN');
$number=Auth::user()->user_phone;
$client = new Client($account_sid, $auth_token);
$messages = $client->messages->create($number, array(
'From' => '+12533368077',
'Body' => Auth::user()->user_otp,
));
dd($messages);
//return $messages;
//throw new Exception();
} catch (Exception $e) {
return response()->json(['error' => true,'message'=>'Something went wrong'],200);
}
}
can you please help me with this
After setting env data did you clear cache?
php artisan config:cache
If you want to handle error - laravel has special logic for that. You need to just to catch that error and then make action, it is simple:
https://laravel.com/docs/5.6/errors
public function render($request, Exception $exception)
{
if ($exception instanceof CustomException) {
return response()->view('errors.custom', [], 500);
}
return parent::render($request, $exception);
}
The app is built on the MVC pattern, so my controllers are separate from my models.
I am using two payment gateways, Stripe and PayPal and have moved the API code into a model called Payment_Model.php.
Both functions have huge try/catch blocks that throw all manner of errors when a payment fails which is a good thing for me, not so for a customer...
Here is a try catch block example
try {
Stripe::setApiKey($this->config->item('stripe_secret_key'));
$customer = Customer::create([
'email' => 'customer#example.com',
'source' => $this->input->post('stripe_token'),
]);
$charge = Charge::create([
'customer' => $customer->id,
'amount' => $option->price,
'currency' => 'eur',
"description" => "Demo Transaction", // #TODO
]);
} catch (Exception $e) {
} catch (Stripe_CardError $e) {
throw new Exception($e);
} catch (Stripe_InvalidRequestError $e) {
throw new Exception($e);
} catch (Stripe_AuthenticationError $e) {
throw new Exception($e);
} catch (Stripe_ApiConnectionError $e) {
throw new Exception($e);
} catch (Stripe_Error $e) {
throw new Exception($e);
} catch (Exception $e) {
throw new Exception($e);
}
I don't want to display these errors or exceptions in my production environment... instead I would like to replace throw new Exception($e) with false so that I can call the model function in my controller and if something goes wrong I can redirect the user to a decent error page...
So my question is this:
Can I return a boolean IF something bad is caught so that I can either redirect to a success page or an error page in my controller? Or am I missing the point of using exceptions?
I've been trying to handle exceptions on cakephp 3 when querying to database.
I would like to get the last query executed when and exception is fired to notify by email to an administrator, i'm using MySQL database so the error code would be nice to have it too if possible.
This is my code right now.
if($this->request->is('post')){
$opciones=$this->request->data;
$configsTable = TableRegistry::get('Configs');
try{
$configsTable->connection()->transactional(function() use($configsTable, $opciones){
foreach ($opciones as $llave => $opcion) {
$q = $configsTable->find('all', [
'conditions' => [
'Configs.nombre' => $llave
]
]);
$reg = $q->first();
if (empty($reg)) {
$data = array();
$data['nombre'] = $llave;
$data['valor'] = $opcion;
$entity = $configsTable->newEntity($data);
if (!$configsTable->save($entity, ['atomic' => false])) {
/********trying to catch database error here******/
throw new \Exception(__('Error message'));
}
}else{
$u = $configsTable->updateAll(['valor'=>$opcion], [
'id'=>$reg->id
]);
if(!$u){
/********trying to catch database error here******/
throw new \Exception(__('Error message'));
}
}
}
});
$this->Flash->success(__('Ajustes actualizados'),[
'params'=>['class'=>'alert-absolute timed', 'tiempo'=>5]
]);
} catch (\PDOException $ex) {
$this->Flash->error($ex->getCode().' - '.$ex->getMessage(),[
//'params'=>['class'=>'alert-absolute timed', 'tiempo'=>5]
]);
} catch (\Exception $ex){
$this->Flash->error($ex->getMessage(),[
//'params'=>['class'=>'alert-absolute timed', 'tiempo'=>5]
]);
}
}
I'm still searching on cookbook for some information. Thaks.
Let the PDOException be handled by the error handler (which is done by default). You can setup your own error handler which checks exception type and sends email in case of PDOException.
You can get the sql query using exception instance as $error->queryString.
My goal is get a JSON like
{
"meta": {
"error_type": "error type",
"code": 400,
"error_message": "error msg"
}
}
In case something went wrong.
I tried to put the try catch block both in the rest controller's action and in the model but I get the whole exception stack (I mean with the layout + view)
What's the right way ?
Catch the exception in the controller action.
Return a JsonModel from the action containing exception information:
public function someAction()
{
try {
throw new Exception();
}
catch (Exception $e) {
return new JsonModel(array(
'meta' => array(
'code' => $e->getCode(),
'error_message' => $e->getMessage(),
//...
)
));
}
//...
}
Source: Returning JSON from a ZF2 controller action
[I tried to put the try catch block both in the action rest
controller]
I've just tried like
(I want my goal become true but
when only if something goes wrong :) )
public function create($data)
{
try{
$artist = $this->getRequest()->getPost('artist', null);
$title = $this->getRequest()->getPost('title', null);
$album = new Album();
$album->exchangeArray(array('artist'=>$artist,'title'=>$title));
$id = $this->getAlbumTable()->saveAlbum($album);
return $this->get($id);
}
catch (Exception $e) {
return new JsonModel(array(
'meta' =>array(
'code'=>500,
'error-num'=>$e->getCode(),
'error-msg'=>$e->getMessage(),
)
));
}
}
but as above it doesn't work
instead of json data i get the
whole default exception stack with layout.