Improve error handling and messages

My thanks to Selwin Ong for pointing out some error handling
improvements that could be made.