5

I'm reading in a YAML file. If there's a syntax mistake that causes an exception, I send the exception to a logger. What is a way to identify in my logging message which line of the YAML file contains the syntax error?

try:
    with open(input_path, "r") as yaml_file:
        yaml_dict = yaml.load(yaml_file)
except FileNotFoundError:
    logger.error("YAML file {} does not exist".format(input_path), exc_info=True)
    sys.exit(1)
except:
    logger.critical("Error in reading or parsing YAML file {}".format(input_path), exc_info=True)
    sys.exit(1)
forest
  • 315
  • 4
  • 14

1 Answers1

5

Have a look at the PyYAMLDocumentation, look for YAMLError():

try:
    yaml.load("unbalanced blackets: ][")
except yaml.YAMLError, exc:
    if hasattr(exc, 'problem_mark'):
        mark = exc.problem_mark
        print "Error position: (%s:%s)" % (mark.line+1, mark.column+1)

Error position: (1:22)
tinita
  • 3,987
  • 1
  • 21
  • 23