Home > database >  How to catch an Exception that is chain called into multiple Classes PHP
How to catch an Exception that is chain called into multiple Classes PHP

Time:11-25

Suppose I have a repository class, a service class, and finally a controller class.

Now, I have a repository class that uses PDO, and I enclosed the execution into a try-catch block, example, below:

MyRepository {
    public function someRepositoryFunction()
    {
        try {
            ...some pdo execution
        } catch (PDOException $e) {
            throw new PDOException($e->getMessage());
        }
    }
}

My question is, when I call that someRepositoryFunction() in the Service class, do I have to enclose it in a try-catch block also? example, below:

MyService {
    public function someServiceFunction()
    {
        $repo = new MyRepository();

        try {
            $repo->someRepositoryFunction();
        } catch (PDOException $e) {
            throw new PDOException($e->getMessage());
        }
    }
}

and finally, when I call the Service class in the Controller, do I also have to enclose the someServiceFunction() in a try-catch block?

Or, catching it in the Repository class enough?

CodePudding user response:

When you catch an Exception, you got 2 options, manage the Exception right were you caught it, according to your app logic or needs or you can throw the exception again and propagate this Exception.

In your case you are throwing the exception again, so you need to catch it again in whatever place you called the method and if you keep throwing the exception up you have to keep catching it.

  • Related