In fact, these are fatal errors - at least as far as they are able to reproduce the correct game; on the other hand, it is possible that the player really made an illegal move, and at that time no one noticed (what would make this warning, and not a fatal mistake).
Given the possibility of both fatal errors (the file is corrupted) and warnings (an illegal move was performed, but subsequent moves show consistency with this movement (in other words, the user's mistake and no one caught it at that time)). I recommend a combination of the first and second options:
- throws an exception if continued parsing is not an option
- collect any errors / warnings that do not prevent further analysis to the end.
If you do not encounter a fatal error, you can return the game, as well as any warnings / non-fatal errors at the end:
return game, warnings, errors
But what if you make a fatal mistake?
No problem: create a custom exception to which you can attach the useful part of the game and any other warnings / non-fatal errors:
raise ParsingError( 'error explanation here', game=game, warnings=warnings, errors=errors, )
then, when you catch an error, you can access the restored part of the game, as well as warnings and errors.
User error may be:
class ParsingError(Exception): def __init__(self, msg, game, warnings, errors): super().__init__(msg) self.game = game self.warnings = warnings self.errors = errors
and when using:
try: first_game, warnings, errors = chess.pgn.read_game(pgn_file) except chess.pgn.ParsingError as err: first_game = err.game warnings = err.warnings errors = err.errors
This is similar to how the subprocess module handles errors.
To be able to extract and analyze subsequent games after a fatal game error, I would suggest changing your API:
- has a game iterator that simply returns raw data for each game (it needs to know how to say when one game ends and the next starts).
- so that the parser takes this raw game data and parses it (so that it is no longer responsible for where you ended up in the file)
Thus, if you have a file of five games and two games, you can still try to analyze games 3, 4, and 5.