Instead of returning the "404 Not Found" string here, you should raise an exception, like ValueError, that is caught in the server loop, so it can then react to it appropriately.