Handle errors reading credentials from ec2 metadata

This add correct error handling for errors trying to access metadata. In order to simplify the implementation it also refactors some existing error handling to use common code.