Try/catch not working with laravel 5.4 - php

I know there are a lot of answers there about this question but none of them really helped me.
// update name
Route::put('/profile/update', function(Request $request){
$name = $request->input('name');
try{
echo DB::table('users')->where('id',Auth::id())->update(['name' => $name]);
}
catch(\Exception $e){
// do task when error
echo $e->get_message();
}
});
I have also tried delete method but that is also not working can you please figure out what is going on.
thanks.

2020 Update
Laravel mostly uses camelCase for nomenclature so use:
catch(\Exception $e){
// do task when error
echo $e->getMessage();
}
If not then just dump full $e to see it through:
catch(\Exception $e){
// do task when error
dd($e);
}
snake_case nomenclature is only used for table names in Laravel.

in my case, I must use \Throwable instead of \Exception
try {
//code
} catch (\Throwable $e) {
dd($e);
}

from your code it seems like the code will never hit the catch which is nothing to do with laravel actually. your issue is a SQL one.
you're trying to update a record and updating a none-existing row will never fail in SQL. so I suggest to handle the case manually by checking the result value and replacing the try and catch with if else
BTW #Learner is 100% right about get_message() it's not in laravel as I know replace it in the future with getMessage()

Change echo $e->get_message(); to echo $e->getMessage();, Exception class dose not have get_message() function.

Related

Why error handling is not working in Laravel

I have set the debug to true on .env file. Added the exceptions correctly but when i am passing invalid or not exist in my database its showing me 404 error but here I put the custom error handling value. Here is my code. (also I put "Use Expectation;" on top so no need of \Expectation)
public function show($id)
{
//only one author with id
try
{
$event = Event::with('eventCategory')->findOrFail($id);
return new EventsResource($event);
//return one author
}
catch(Expectation $e)
{
report($e);
return response()->json(['status'=> false, 'message'=>'invalid data'],200);
}
}
Do you mean Exception? Because in your question it's Expectation...
As #user3532758 is implying, you probably want to be catching the base Exception not Expectation.
Also make sure you are referencing Exception from the root namespace, assuming the code you have shown is in a Controller:
try {
...
} catch (\Exception $e) {
...
}
PHP Manual - Classes - Exception

Laravel 5 - try catch exception not working

I am new to laravel5 and this code fails to catch all the exceptions.
I don't know what's wrong, please help.
public function delete($id)
{
$sql = $this->deleteSql();
DB::beginTransaction();
try {
$deleteData = Db::delete($sql, ['id' => $id]);
if (!$deleteData) {
return false;
}
return true;
} catch (\Exception $e) {
DB::rollback();
return $e->getMessage();
}
DB::commit();
}
It will give me :
Illuminate\Database\QueryException: SQLSTATE[22P02]:
and
Caused by
PDOException: SQLSTATE[22P02]:
Your method is not going to catch block at all since it is returning bool from try block.
Also I don't know what made you use try...catch block.
I more error:
Db::delete($sql, ['id' => $id]);
If you have defined Db, then it is okay. But if not, then it will throw error.
Also there is no need to use transactions, unless you are testing your application with any PHP Testing tool like phpUnit / phpSpec, etc.
Solution:
There is no need to use try..catch block at all.
Just call the delete method on the model that you wish to delete, and you will be done, like so:
public function delete($id)
{
YourModel::delete($id); // Replace YourModel with the model you wish to delete
\Session::flash('delete_message', 'Model has been successfully deleted.');
return redirect()->back(); // or anywhere else of your choice
}
Hope this helps you out. Happy Coding. Cheers.

php code logic by version

I want a solution something like: Imagine I have try catch block, it works in any php 5.?.? version but with finally block not in any. my code must be like this:
try {
// some logic
} catch (Exception $ex) {
// some logic
} finally {
// other logic
}
but, how can I make so that finally block worked only if php version supports it else ignore? For example:
try {
// some logic
} catch (Exception $ex) {
// some logic
}
#if version=5.?.?
finally {
// other logic
}
#endif
Is there any solution?
You can get php version by phpversion method. The only option you have is to write an if statement to check it; if it supports write the whole try-catch-finally block. If it does not, write only try-catch. You can use inline functions to prevent duplicate code. I have no idea why somebody needs this, but for example;
function fncTry(){...}
function fncCatch($exception){...}
function fncFinally(){...}
if($phpVersion == '5.5'){
try { fncTry(); }
catch(Exception $ex) { fncCatch($ex); }
finally { fncFinally(); }
}else{
try { fncTry(); }
catch(Exception $ex) { fncCatch($ex); }
fncFinally();
}
Yes.
phpversion() will return a string of the php version. (Example: "5.6.14")
You can use that to set up your conditional statement.
i am sorry i'm confused :)
check this
and you could check about phpversion before you make the try catch
if (php version == 5.5 or greater)
you make it with finally
else you make it without finally

Laravel DB::transaction() return value

It's my first time to use DB::transaction() but how exactly does it work if a transaction fails or is successful? In the example below, do I have to manually assign a value to return true, or if it fails will the method either return false or totally exit the transaction (therefore skipping the rest of the code)? The docs aren't so helpful on this.
use Exception;
use DB;
try {
$success = DB::transaction(function() {
// Run some queries
});
print_r($success);
} catch(Exception $e) {
echo 'Uh oh.';
}
Solution
I wrote down this solution for others who might be wondering.
Since I was more concerned about returning a boolean value depending on the success of my query, with a few modifications it now returns true/false depending on its success:
use Exception;
use DB;
try {
$exception = DB::transaction(function() {
// Run queries here
});
return is_null($exception) ? true : $exception;
} catch(Exception $e) {
return false;
}
Take note that the variable $exception is never returned since if something goes wrong with your query, the catch is immediately triggered returning false. Thanks to #ilaijin for showing that an Exception object is thrown if something goes wrong.
By giving a look at function transaction it does its process inside a try/catch block
public function transaction(Closure $callback)
{
$this->beginTransaction();
// We'll simply execute the given callback within a try / catch block
// and if we catch any exception we can rollback the transaction
// so that none of the changes are persisted to the database.
try
{
$result = $callback($this);
$this->commit();
}
// If we catch an exception, we will roll back so nothing gets messed
// up in the database. Then we'll re-throw the exception so it can
// be handled how the developer sees fit for their applications.
catch (\Exception $e)
{
$this->rollBack();
throw $e;
}
So throws an Exception (after the rollback) if fails or returns $result, which is the result of your callback
There is a short version if you want to use the default transaction method that ships with Laravel without handling it manually.
$result = DB::transaction(function () {
// logic here
return $somethingYouWantToCheckLater;
});
You can also use the following
DB::rollback();

Balanced Payments PHP Client: query result triggers uncaught exception

I'm trying to query a marketplace for an account that matches an e-mail address, and when it can't find a result, it's raising an uncaught exception despite my try/catch block.
try {
$vendor = $this->marketplace ->accounts ->query()
->filter(Balanced\Account::$f->email_address->eq($this->vendor['email']))
->one();
$this->balanced_vendor = $vendor;
return true;
} catch (Balanced\Exceptions\HTTPError $e) {
$this->notify('no-vendor', $e);
}
What might i be doing wrong ?
Thanks !
Looks like the Balanced\Core\Query class throws both Balanced\Exceptions\MultipleResultsFound and Balanced\Exceptions\NoResultFound from its one() method, not Balanced\Exceptions\HTTPError.
To fix your immediate problem, you should change your catch directive to:
} catch (Balanced\Exceptions\MultipleResultsFound $e) {
// handle multiple results..
} catch (Balanced\Exceptions\NoResultsFound $e) {
$this->notify('no-vendor', $e);
}
From the looks of it though, you attempted to use the Balanced\Exceptions\HTTPError as a catch all, which can be considered a lacking feature of the client. What I've done, is I've filed a Github issue for you that suggest all exceptions inherit from a base Balanced exception.
I hope this helps.

Categories