Improve error diagnosis and generalization

Change-Id: Idc7b71283721f1683bc30cb1d412af0120318273