Php Exception Catcher / Router

I guess its more like an exception router. A single class that's used to catch all exceptions in a program & makes it really easy to convert stack traces into informative error messages.

It could also help to have testing associated with it. Like, maybe I want to make sure it throws the right exceptions & that my informative error hasn't been ruined by changes to the code (like a new class name, or changed line number, etc)

This is just an idea. I don't know if I'll make it. You're welcome to make it. If you wanna @ me, I'm @TaelufDev on twitter.

Example:

Sample error

ErrorException: 
    Uninitialized string offset: 0 
        in .../Lexer/InstructionProcessor.php:137

This particular Exception means there is an empty instruction in the grammar. So instead of writing 'rewind 1', there's an empty string like ''.

Of course, we could do an if & make sure the string is non-empty before doing $string[0] to access the first char, but you're not allowed to have an empty instruction, per terms of the Lexer. So this would be an extra branch, harming performance, without actually making the program run any better.

How it might work

My Lexer could put a try{}catch{} around its while($token->next()) loop. The catch would look something like:

catch (\Throwable t){
    $myCatcher = new Catcher(); //subclass of the main catcher class
    $myCatcher->throw($t);
}

Or maybe it uses a config file instead of subclassing, or some other approach of extensibility.

It also may be necessary to set an error_handler for non-exception errors.

Some other notes

The Catcher would need some kind of interface to make it simple to respond to the following elements of an exception:

  • Class of the exception
  • File its thrown in
    • Line number in said file
    • possibly respond to a range, like line 130 - 145, so if the code moves a little bit, the exception is still handled.
  • The exception's message
  • (maybe) Any of the line-numbers / files / call's listed in the stack trace
    • Rather than a built-in extensibility for these, maybe just provide a simple-to-use API to access these and handle your own routing of these more complex scenarios.