Ad

How Stop CognitoIdentityProviderException From Returning 500 Status Code In AWS PHP Sdk

I am developing a Web application. In my app, I need to login user to the AWS cognito system. I can log in to the system successfully. But the only problem is when the username and password provided by the user are not valid, my Laravel framework kills the application returning 500 internal server status code. But I want to do something else when the username and password are not valid. I tried using try catch block, but it is not overriding the error. Please, see my code below.

try{

                $client = new CognitoIdentityProviderClient([
                    'version' => 'latest',
                    'region' => env('AWS_REGION', '')
                    'credentials' => [
                        'key'    => env('AWS_IAM_KEY', ''),
                        'secret' => env('AWS_IAM_SECRET', '')
                    ]
                ]);

                $result = $client->adminInitiateAuth([
                    'AuthFlow' => 'ADMIN_NO_SRP_AUTH',
                    'ClientId' => COGNITO_APP_CLIENT_ID,
                    'UserPoolId' => COGNITO_USER_POOL_ID,
                    'AuthParameters' => [
                    'USERNAME' => $request->email,
                    'PASSWORD' => $request->password,
                ],
                ]);
                //Error thrown here if the  username and password are not valid.
                //continue

            }
            catch(Exception $e)
            {
                //I want to do something here if the error is thrown because of the invalid credentials without killing the app by throwing 500 status code.
            }

As you can see in the above code if the user credentials are not valid, the SDK will throw the error. It will kill the app by returning 500 status code. I do not want to stop there. So, I used the try catch block to catch the error and continue in the code. But the try catch block is not catching the error as well.

This is the screenshot. enter image description here

So, how can I stop the AWS sdk from stopping the application throwing 500 status code?

Ad

Answer

Finally, I found the solution. Laravel works with namespaces. So, instead of using just Exception in the try catch block, I needed to put "\" as a prefix. So the try catch becomes like this.

try{
   //code
}
catch(\Exception $e) //pay attention to the "\"
{
}
Ad
source: stackoverflow.com
Ad