i have function a
with try/catch block , it’s calling function b
which has it’s own try/catch block … when exception happens in function b
i want to activate catch block in the function a
so i can log my errors from single line
function a(){
try
{
doo stuff
$this->b();
}
catch (Exception $exception)
{
//ErrorLog | line / message / file
}
}
function b(){
DB::beginTransaction();
try
{
db insert
DB::commit();
}
catch (Exception $exception)
{
DB::rollBack();
}
}
my question is how can i pass exception from function b
to catch block in function a
? i can throw new exception from catch block
catch (Exception $exception)
{
DB::rollBack();
throw new Exception("something wrong in function b");
}
but it’s not going to contain error data
2
Answers
You can just re-throw the exception…
There are 2 options which you can do it with.
Rethrowing the same exeption
You can re-throw an exception using the throw keyword without any arguments inside the catch block of method
b
. This will re-throw the same exception that was caught in the catch block on methodb
, allowing you to catch it again in an outer try/catch block of methoda
.Here is how you can do it:
In this example, we create a new Exception object with a custom message and pass the original exception as the third argument to the constructor. This preserves the original exception’s type and stacktrace, while adding additional information to the message.
Throwing a custom exception
Here is how you can do it: