gcode_macro: Catch variable encoding errors

Catch parsing and json encoding errors at variable assignment.

Signed-off-by: Justin Schuh <code@justinschuh.com>
This commit is contained in:
Justin Schuh 2023-04-12 07:27:15 -07:00 committed by KevinOConnor
parent d68a6c28ba
commit c2fe372925
1 changed files with 11 additions and 8 deletions

View File

@ -3,7 +3,7 @@
# Copyright (C) 2018-2021 Kevin O'Connor <kevin@koconnor.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import traceback, logging, ast, copy
import traceback, logging, ast, copy, json
import jinja2
@ -144,12 +144,13 @@ class GCodeMacro:
prefix = 'variable_'
for option in config.get_prefix_options(prefix):
try:
self.variables[option[len(prefix):]] = ast.literal_eval(
config.get(option))
except ValueError as e:
literal = ast.literal_eval(config.get(option))
json.dumps(literal, separators=(',', ':'))
self.variables[option[len(prefix):]] = literal
except (SyntaxError, TypeError, ValueError) as e:
raise config.error(
"Option '%s' in section '%s' is not a valid literal" % (
option, config.get_name()))
"Option '%s' in section '%s' is not a valid literal: %s" % (
option, config.get_name(), e))
def handle_connect(self):
prev_cmd = self.gcode.register_command(self.alias, None)
if prev_cmd is None:
@ -169,8 +170,10 @@ class GCodeMacro:
raise gcmd.error("Unknown gcode_macro variable '%s'" % (variable,))
try:
literal = ast.literal_eval(value)
except ValueError as e:
raise gcmd.error("Unable to parse '%s' as a literal" % (value,))
json.dumps(literal, separators=(',', ':'))
except (SyntaxError, TypeError, ValueError) as e:
raise gcmd.error("Unable to parse '%s' as a literal: %s" %
(value, e))
v = dict(self.variables)
v[variable] = literal
self.variables = v