user defined errors

This is a rebased PR of #722 
I'll manage changes