Slightly modularize error counting

(cherry picked from commit 637bd7928736a6952e61f6501c48c97eec2f49fe)