This question is related to the Cactus Text Game Engine.
For easy error handling in Cactus, we've put together this small decorator. Essentially, the decorator wraps any class method in a try-except
block, which reports errors to a log file if something goes wrong. While it's a small file, I can't help but feel that it's a little monolithic, and slightly ugly as well.
from contextlib import redirect_stdout
from traceback import format_exc
from pprint import pformat
from sys import exit, maxsize
from os import path
from time import strftime
import platform
def _cactus_class_method_exception_handle(function):
"""
This function provides a general wrapper for
handling errors with the Cactus engine. Example
usage:
@_cactus_class_method_exception_handle
def my_class_method(self, args):
code
"""
def wrapper(self, *args, **kwargs):
try:
return function(self, *args, **kwargs)
except Exception as cactus_game_error:
date_string = strftime("%H_%M_%S_%b_%d_%y")
print("\n" + "=" * 50 + "\n")
print("Something wrong internally happened. (This may or may not be your fault!). This may be an issue with the game itself, or the")
print("underlying components. To help fix this issue, please contact the developers of the game with the error report.")
print("")
print("In your error report, please include the file:")
print(path.abspath("cactus_error_log_" + date_string +".txt"))
print("\n" + "=" * 45 + "\n")
with open("cactus_error_log_" + date_string +".txt", "w+") as cactus_error_log:
with redirect_stdout(cactus_error_log):
print("\n" + "=" * 45 + "\n")
print("CACTUS GAME ENGINE ERROR REPORT")
print("")
print("If you think this error is engine-related,")
print("please report it to:")
print("https://github.com/ShearOfDoom/Cactus/issues/")
print("\n" + "=" * 45 + "\n")
print("Date/Time: {0}".format(strftime("%c")))
print("Operating System: {0}".format(platform.platform()))
print("Processor: {0}".format(platform.processor()))
print("System [not Python itself] 32 or 64 bit: {0}".format(platform.machine()))
print("Is 64-bit Python?: {0}".format(maxsize > 2**32))
print("Python: {0} {1} {2} {3}".format(platform.python_implementation(), platform.python_build()[0], platform.python_build()[1], platform.python_compiler()))
print("\n" + "=" * 45 + "\n")
print("CLASS DATA:", pformat(self.class_data, indent = 2))
print("\n" + "=" * 45 + "\n")
print("STACK TRACE:", format_exc())
print("=" * 45 + "\n")
exit(0)
return wrapper
Here's a simple example of the output this function will produce when it encounters an error of any kind.
============================================= CACTUS GAME ENGINE ERROR REPORT If you think this error is engine-related, please report it to: https://github.com/ShearOfDoom/Cactus/issues/ ============================================= Date/Time: 06/11/15 18:14:59 Operating System: Windows-8-6.2.9200 Processor: Intel64 Family 6 Model 69 Stepping 1, GenuineIntel System [not Python itself] 32 or 64 bit: AMD64 Is 64-bit Python?: False Python: CPython v3.4.3:9b73f1c3e601 Feb 24 2015 22:43:06 MSC v.1600 32 bit (Intel) ============================================= CLASS DATA: { 'about_text': 'Write about your game here.', 'allow_help': True, 'case_sensitive': False, 'desc': 'Game Description', 'event_handlers': { 'position.name goes here 1.enter.after': <built-in function exit>, 'position.name goes here 2.enter.after': <built-in function exit>}, 'flowchart': <cactus.flowchart.Flowchart object at 0x02A00F30>, 'invalid_input_msg$': 'Invalid input', 'name': 'Game Name', 'prompt': '> '} ============================================= STACK TRACE: Traceback (most recent call last): File "C:\Users\...\Desktop\Git-Projects\Cactus\cactus\errors.py", line 21, in wrapper return function(self, *args, **kwargs) File "C:\Users\...\Desktop\Git-Projects\Cactus\cactus\game.py", line 54, in _check_class_data raise KeyError("Could not find key {0} in class data.".format(item[0])) KeyError: 'Could not find key invalid_input_msg in class data.' =============================================
try: ... except: ...
in the top-level loop? \$\endgroup\$try-except
block. \$\endgroup\$