Hooks are intentionally removed from post-command-hook because otherwise a bad hook could lead to a condition where it becomes impossible to do anything, including figuring out what is going wrong, because the errors happens when ever the user does anything what-so-ever...
There might be other possible causes for errors in your function but one I noticed immediately is that you use beginning-of-defun and end-of-defun and assume these always return buffer positions. That does not have be the case, they can also return nil when there is no "defun" around.