Refine error handling and fix some indentation.