Proper error codes

Switch Json API to a proper error code reporting system and enhance API type safety.