mercredi 4 octobre 2017

In PHP is there a way I can avoid repeating the same try / catch code in multiple methods of a class?

I've been searching for an existing question that already asks this, but I wasn't able to find any questions that quite ask what I'm trying to figure out. The most similar question I could find was this: php 5.3 avoid try/catch duplication nested within foreach loop (code sandwich)

Okay so the place I work at has a web application with a PHP back end. We use an MVC type structure. I'm writing a controller that has multiple methods and in each of my methods I'm wrapping my code with identical try / catch code. In the catch, I pass the exception, a reference to the class, and a reference to the function to a method that builds an error message so that the error messages are formatted the same across the application. It looks something this:

class MyController {

    public function methodA() {
        try {
            // code for methodA
        } catch(Exception $e) {
            $errorMessage = Tasks::buildErrorMessage($e, __CLASS__, __FUNCTION__);
            throw new Exception($errorMessage);
        }
    }

    public function methodB() {
        try {
            // code for methodB
        } catch(Exception $e) {
            $errorMessage = Tasks::buildErrorMessage($e, __CLASS__, __FUNCTION__);
            throw new Exception($errorMessage);
        }
    }

    public function methodC() {
        try {
            // code for methodC
        } catch(Exception $e) {
            $errorMessage = Tasks::buildErrorMessage($e, __CLASS__, __FUNCTION__);
            throw new Exception($errorMessage);
        }
    }

}

So the buildErrorMessage function prevents each method from repeating the code that formats the error message, but there is something that really bothers me about have the same code spread through out every method in the class. I know that PHP doesn't support python-like decorator syntax, but just to demonstrate what I'm envisioning conceptually; I want the code to behave something more like this:

class MyController {

    @DefaultErrorHandling()
    public function methodA() {
        // code for methodB
    }

    @DefaultErrorHandling()
    public function methodB() {
        // code for methodB
    }

    @DefaultErrorHandling()
    public function methodC() {
        // code for methodC
    }

}

Where the @DefaultErrorHandling decorator would wrap each method in that standard try / catch. Is there a way I could achieve this behavior so I don't have to have all of these methods that have repeated code? Or am I thinking about error handling incorrectly?

Thanks to anyone who takes the time to answer this.

Aucun commentaire:

Enregistrer un commentaire