ReedyBear's Blog

Overcomplicating code

I have long had a tendency to significantly overcomplicate my code. Like this idea for error handling. It wasn't necessarily a bad idea, it just was overcomplicated and unnecessary.

Instead of having a json file that holds all of my errors, then referencing them by string, and writing some additional code to manage this mess - just subclass Exception, and define a bunch of variables on the class that describe each error.

So instead of a json file with:

{
    "NoRoutesFound": {
        "ExceptionMessage": "No routes were found for the request to %s",
        "UserMessage": "Page not found.",
        "HelpDocs": "https://liaison.reedybear.com/error/NoRoutesFound" 
    }
    ... other errors
}

I would have something like:

<?php

class MyException extends \Exception {

     public array $active_error;

     static public $err_no_routes_found = 
         [ "ExceptionMessage" => "No routes were found for the request to %s"
           "UserMessage" => "Page not found."
           "HelpDocs": "https://liaison.reedybear.com/error/NoRoutesFound" 
         ]
    // other errors

    public function __construct(array $error){
          $this->active_error = $error;
          parent::__construct($error['ExceptionMessage']);
    }
    public function get_user_message(): string{
        return 
           $this->active_error['UserMessage'] 
           ."\n<br>Get Help at <a href=\""
            .$this->active_error['HelpDocs']
           ."\">"
           . $this->active_error['HelpDocs']
           ."</a>";
}

Then in my try/catch I'd just print $e->user_message();.

P.S. Probably better to have a parent class like the above, then define a bunch of exception subclasses that have defined properties and then I just throw the named subclass. I'd end up having a ton of different exception subclasses, but SO WHAT. It would be simple, even if a bit boilerplate heavy.

#blog #code