template: handle render exceptions

Re-raise as either a ServerError or ConfigError as appropriate.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
This commit is contained in:
Eric Callahan 2023-02-14 14:02:44 -05:00
parent a40dae2bc8
commit 87dba2f2e2
No known key found for this signature in database
GPG Key ID: 5A1EB336DFB4C71B
2 changed files with 21 additions and 3 deletions

View File

@ -5,6 +5,7 @@
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import logging
import asyncio
import jinja2
import json
@ -89,10 +90,21 @@ class JinjaTemplate:
raise self.server.error(
"Cannot render async templates with the render() method"
", use render_async()")
return self.template.render(context).strip()
try:
return self.template.render(context).strip()
except Exception as e:
msg = "Error rending Jinja2 Template"
if self.server.is_configured():
raise self.server.error(msg, 500) from e
raise self.server.config_error(msg) from e
async def render_async(self, context: Dict[str, Any] = {}) -> str:
ret = await self.template.render_async(context)
try:
ret = await self.template.render_async(context)
except asyncio.CancelledError:
raise
except Exception as e:
raise self.server.error("Error rending Jinja2 Template", 500) from e
return ret.strip()
def load_component(config: ConfigHelper) -> TemplateFactory:

View File

@ -57,6 +57,7 @@ SENTINEL = SentinelClass.get_instance()
class Server:
error = ServerError
config_error = confighelper.ConfigError
def __init__(self,
args: Dict[str, Any],
log_manager: LogManager,
@ -69,6 +70,7 @@ class Server:
self.components: Dict[str, Any] = {}
self.failed_components: List[str] = []
self.warnings: Dict[str, str] = {}
self._is_configured: bool = False
self.config = config = self._parse_config()
self.host: str = config.get('host', "0.0.0.0")
@ -124,6 +126,9 @@ class Server:
def is_running(self) -> bool:
return self.server_running
def is_configured(self) -> bool:
return self._is_configured
def is_debug_enabled(self) -> bool:
return self.debug
@ -238,6 +243,7 @@ class Server:
self.klippy_connection.configure(config)
config.validate_config()
self._is_configured = True
def load_component(self,
config: confighelper.ConfigHelper,
@ -259,7 +265,7 @@ class Server:
if component_name not in self.failed_components:
self.failed_components.append(component_name)
if isinstance(default, SentinelClass):
raise ServerError(msg)
raise
return default
self.components[component_name] = component
logging.info(f"Component ({component_name}) loaded")