Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Google resource manager get all exceptions – Python

im making a python script that can manage my google projects.
im having a insue with one part
when i try to exclude the project its can return to me many errors.

i did a peace of code to get this exception:

        try:
            # Initialize request argument(s)

            request = DeleteProjectRequest(
                name=project,
            )
            self.project_manager.delete_project(request=request)

        except PermissionDenied as exc:
            # GCP returns PermissionDenied whether we actually does
            # not have permissions to perform the get_project call
            # or when the project does not exist. Due to this reason,
            # the PermissionDenied exception catch won't be deterministic.
            logger.error(f"Project '{project_id}' does not exist", exc)
            return False

i need to get the error message of all types of errors
i changed except PermissionDenied as exc: for except Exception as exc:
and it works but i need to call the logger only if the error is PermissionDenied and in all cases i need to call another function passing the message as parameter like it return_to_db(error_message)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

my question is. how can i run only the logger if the error is PermissionDenied?

>Solution :

You can add a condition of the instance type of the current exception in Python, example :

        try:
            # Initialize request argument(s)

            request = DeleteProjectRequest(
                name=project,
            )
            self.project_manager.delete_project(request=request)

        except Exception as exc:
            if isinstance(exc, PermissionDenied):
               logger.error(f"Project '{project_id}' does not exist", exc)
            
        return False

As expected, the logger is executed only if the exception instance is PermissionDenied.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading