I have code that requires a lot of repeated code such as try and catch exceptions. Looking at the code below could I put the try and catch exception into a function to keep it clean?
public function home(){
try{
$variable = DB::table($tableone)->first();
}catch(\Exception $e){
}
//some code
try {
$variabletwo = DB::table($tabletwo)->first();
}catch(\Exception $e){
}
//some code
try {
$variablethree = DB::table($tablethree)->first();
}catch(\Exception $e){
}
}
function GetFirst($tbl) {
try
{
return DB::table($tbl)->first();
}
catch (Exception $e)
{ ... }
}
$variableone = GetFirst($tableone);
$variabletwo = GetFirst($tabletwo);
You should only make one try catch for the whole block.
You can refer to this answer for best practice on try catch.
Related
Hay I'm creating a code like this :
\Log::info("saving log....");
try{
$data = AstronautCandidateLog::insert($request->logs);
}catch (SQLException $e)
{
\Log::info("SQL Exception happened");
}catch (Exception $e)
{
\Log::info("Exception happened");
}
\Log::info("status save data : ". $data);
But it seems that my Exception never get hit. So how to capture exception in laravel when something wrong in sql query...??
Thanks in advance.
Try this
try {
//Your code
} catch(\Illuminate\Database\QueryException $ex){
dd($ex->getMessage());
}
OR
use Illuminate\Database\QueryException;
try {
//Your code
} catch(QueryException $ex){
dd($ex->getMessage());
}
My case: add \ before Exception class otherwise it not handle
try
{
//write your codes here
}
catch(\Exception $e) {
Log::error($e->getMessage());
}
Make sure to use the Exception library in your controller. From there you can do:
try{
Some queries . . .
}catch(Exception $e){
return response()->json([
'error' => 'Cannot excecute query',
],422);
}
To implement an exception in Laravel, simply include the Exception class, at the top of your controller as
Use Exception;
Then wrap the lines of code you wish to catch an exception on using try-catch statements
try
{
//write your codes here
}
catch(Exception $e)
{
dd($e->getMessage());
}
You can also return your errors in json format, incase you are making an Ajax request, this time, remember to include the Response class at the top of your controller
Use Response;
Use Exception;
then wrap your codes in a try-catch statement as follows
try
{
//write your codes here
}
catch(Exception $e)
{
return response()->json(array('message' =>$e->getMessage()));
}
I hope this will solve your problem, you can learn more on Laravel and Error handeling here
I have the following code -
public function getPosts($limit = 25, $author = null) {
try {
} catch(\GuzzleHttp\Exception\ClientException $e) {
return [];
}
return [];
}
I added this b/c when the page 404s I get the ClientException, however if the server returns a 500 error I get a ServerException - I tried just replacing this with catch(Exception $ex), but I still get the unhandled/uncaught exception error.
You can have multiple catch blocks for different exception types in php:
try {
} catch(\GuzzleHttp\Exception\ClientException $e) {
return [];
} catch(\GuzzleHttp\Exception\ServerException $e) {
//handle it...
}
However, the assuming the Guzzle exceptions extend the general php Exception class (which of course they do), changing it to just Exception $e should work. Are you sure this is where the exception is being thrown?
On the guzzle site http://docs.guzzlephp.org/en/latest/quickstart.html#exceptions you can see GuzzleHttp\Exception\TransferException base for all the client/server extensions, so you could just try to catch a GuzzleHttp\Exception\TransferException;
just list multiple catches:
try {
...
} catch (FooException e) {
...
} catch (BarException e) {
...
} catch (Exception e) {
...
}
Just keep catching
public function getPosts($limit = 25, $author = null) {
try {
} catch(\GuzzleHttp\Exception\ClientException $e) {
return [];
} catch (ServerException) {
//some code
}
return [];
}
be aware of namespaces, if you try to catch Exception it will catch all exceptions, if it did not, maybe you didnt include the exception as use Exception or tried to catch \Exception
The catch can be chained one after the other for handling multiple Error Types.
public function getPosts($limit = 25, $author = null) {
try {
} catch(\GuzzleHttp\Exception\ClientException $e) {
return [];
} catch(\GuzzleHttp\Exception\ServerException $e) {
return [];
}
return [];
}
Is this possible in PHP?
try {
$obj = new Clas();
if ($obj->foo) {
// how to exit from this try block?
}
// do other stuff here
} catch(Exception $e) {
}
I know I can put the other stuff between {}, but that increases indenting on a bigger code block and I don't like it :P
With a goto of course!
try {
$obj = new Clas();
if ($obj->foo) {
goto break_free_of_try;
}
// do other stuff here
} catch(Exception $e) {
}
break_free_of_try:
Well, there is no reason for that, but you can have fun forcing an exception in your try block, stopping execution of your function.
try {
if ($you_dont_like_something){
throw new Exception();
//No code will be executed after the exception has been thrown.
}
} catch (Exception $e){
echo "Something went wrong";
}
I also faced this situation, and like you, didn't want countless if/else if/else if/else statements as it makes the code less readable.
I ended up extending the Exception class with my own. The example class below was for validation problems that when triggered would produce a less severe 'log notice'
class ValidationEx extends Exception
{
public function __construct($message, $code = 0, Exception $previous = null)
{
parent::__construct($message, $code, $previous);
}
public function __toString()
{
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
}
In my main code I call it;
throw new ValidationEx('You maniac!');
Then at the end of the Try statement I have
catch(ValidationEx $e) { echo $e->getMessage(); }
catch(Exception $e){ echo $e->getMessage(); }
Happy for comments and criticisms, we're all here to learn!
try
{
$object = new Something();
if ($object->value)
{
// do stuff
}
else
{
// do other stuff
}
}
catch (Exception $e)
{
// handle exceptions
}
Couldn't you just do like this?
try{
$obj = new Clas();
if(!$obj->foo){
// do other stuff here
}
}catch(Exception $e){
}
In php 5.3+ the nice thing about using exceptions with a try catch block, is that you can make your own Exceptions and handle them how and when you want. See: Extending Exceptions
class AcceptedException extends \Exception
{
//...
}
You can then catch specific exceptions or use if ($e instanceof AcceptedException) within your catch \Exception block to determine how you want to handle the exception(s).
Handled Example: http://ideone.com/ggz8fu
Unhandled Example: http://ideone.com/luPQel
try {
$obj = (object) array('foo' => 'bar');
if ($obj->foo) {
throw new \AcceptedException;
}
} catch (\AcceptedException $e) {
var_dump('I was accepted');
} catch (\Exception $e) {
if ($e instanceof \InvalidArgumentException) {
throw $e; //don't handle the exception
}
}
This makes your code much more readable and easier to troubleshoot as opposed to a lot of alternative solutions.
Personally I like to exit try/catch statements by using a
throw new MyException("optional message", MyException::ERROR_SUCCESS);
which I obviously catch by using:
switch($e->getCode()) {
/** other cases make sense here */
case MyException::ERROR_SQL:
logThis("A SQL error occurred. Details: " . $e->getMessage());
break;
case MyException::ERROR_SUCCESS:
logThis("Completed with success. Details: " . $e->getMessage());
break;
case MyException::ERROR_UNDEFINED:
default:
logThis("Undefined error. Details: " . $e->getMessage());
break;
}
This is the way I'd do that :
<?php
echo 'this' . PHP_EOL;
switch(true) {
default:
try {
echo 'is' . PHP_EOL;
break;
echo 'not' . PHP_EOL;
} catch (Exception $e) {
// error_log($e->getMessage());
}
}
echo 'fun !';
:-)
Let's say I have codes like this:
try{
doTaskA();
doTaskB();
doTaskC();
} catch(MyException $e){
fixMyException();
}
When doTaskA() throws MyException, I want the program to go through fixMyException(), then it goes back and continues executing doTaskB() and doTaskC(). Is it possible?
The same thing should apply to other tasks, i.e. all doTaskA/B/C() may throw the same exception, and I want the program can go on to the unfinished tasks every time after it executes fixMyException()..
Is there any thing like "continue" or "resume" function in the exception handling?
I have checked the PHP manual but it seems such control structure doesn't exist. If so, what's the best practice to design the program that can do what I want? (Supposed I have over 10 taskes inside the try block).
function do_all_tasks($position=0)
{
$tasks = array('doTaskA', 'doTaskB', 'doTaskC', ...);
$size = count($tasks);
for ($i=$position; $i<$size; ++$i)
{
try
{
$func = $tasks[$i];
$func();
}
catch (Exception $e)
{
fixMyException();
do_all_tasks($i+1);
};
}
}
do_all_tasks();
try{
doTaskA();
} catch(MyException $e){
fixMyException();
}
try{
doTaskB();
} catch(MyException $e){
fixMyException();
}
try{
doTaskC();
} catch(MyException $e){
fixMyException();
}
How is that any different than doing
try {
doTaskA();
} catch (MyException $e) {
fixMyException();
}
try {
doTaskB();
} catch (MyException $e) {
fixMyException();
}
try {
doTaskC();
} catch (MyException $e) {
fixMyException();
}
No it is not possible. You'd need to put each of doTask*() functions in it's own separate try-catch block.
I have the following function:
public function getClientTable($feedUrl)
{
$client = new Zend_Http_Client($feedUrl);
try
{
return $client->request()->getBody();
}
catch (Zend_Http_Client_Adapter_Exception $e)
{
return false;
}
}
It seems to work great for catching that specific Zend_Http_Client_Adapter_Exception; but what if I want it to catch additional exceptions? Hell, what if I wanted it to catch ALL exceptions... how would I do this?
Also, should I be using "return" or "throw" in the try? Why does it matter?
You can have multiple catch statements, eg
try {
// whatever
} catch (Zend_Http_Client_Adapter_Exception $e) {
// ah ha
} catch (Zend_Some_other_Exception $e) {
// ah ha
} catch (Exception $e) {
// And the final fallback catch that grabs all exceptions
}