Fix tests and improve error handling