I have implemented the method below inside a Laravel controller.
function update(Request $req)
{
try {
$resp = new stdClass();
$resp->b->a = 1;
} catch ( Exception $ex) {
return response('An error has occured.' . $ex->getMessage(), 400);
}
}
The $resp->b->a = 1
triggers a "Attempt to assign property on null" exception which is supposed to be gracefully handled by the catch block, and a response code 400 with an explicit message should be returned to the client.
However, in my case, an error code 500 (Internal server error) is thrown to the client; which clearly indicates that the catch block is being skipped.
If I change the function to
function update(Request $req)
{
try {
throw new Exception("Exception Message");
} catch ( Exception $ex) {
return response('An error has occured.' . $ex->getMessage(), 400);
}
}
the exception is gracefully handled by the catch block.
Your help is appreciated.
2
Answers
I have managed to solve the issue by trial and error. The classes Exception and Error both implement the Throwable interface. This means, if you want to catch both Error instances and Exception instances, you should also catch Throwable objects. Updated function:
Most likely the thrown exception is not an instance of
Exception
. Try catch blocks will not catch exceptions that don’t match the type provided in the catch block.P.S. You cannot directly create sub-objects in stdClass objects.