Fixed #22058 -- Refactored handlers and created a generic mechanism to deal with server/client errors.

Thanks Aymeric Augustin for the idea and Tim Graham for review.