skip to Main Content

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


  1. Chosen as BEST ANSWER

    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:

      function update(Request $req)
        {
            try {
              
                throw new Exception("Exception Message");
               
            } catch (Throwable  | Exception $ex) {
                return response('An error has occured.' . $ex->getMessage(), 400);
            }
        }
    

  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search