fix error handling and reformat code

fix error handling and reformat code