dbt exceptions macro 简单说明
dbt exceptions 实际属于一个namespace 变量可以进行一些代码可控的异常处理以及raise 以及warn
参考使用
- raise_compiler_error 使用
{% if number < 0 or number > 100 %}
{{ exceptions.raise_compiler_error("Invalid `number`. Got: " ~ number) }}
{% endif %}
内部实现
属于一个上下文属性
- 参考代码
@contextproperty()
def exceptions(self) -> Dict[str, Any]:
"""The exceptions namespace can be used to raise warnings and errors in
dbt userspace.
## raise_compiler_error
The `exceptions.raise_compiler_error` method will raise a compiler
error with the provided message. This is typically only useful in
macros or materializations when invalid arguments are provided by the
calling model. Note that throwing an exception will cause a model to
fail, so please use this variable with care!
Example usage:
> exceptions.sql:
{% if number < 0 or number > 100 %}
{{ exceptions.raise_compiler_error("Invalid `number`. Got: " ~ number) }}
{% endif %}
## warn
The `exceptions.warn` method will raise a compiler warning with the
provided message. If the `--warn-error` flag is provided to dbt, then
this warning will be elevated to an exception, which is raised.
Example usage:
> warn.sql:
{% if number < 0 or number > 100 %}
{% do exceptions.warn("Invalid `number`. Got: " ~ number) %}
{% endif %}
""" # noqa
return wrapped_exports(self.model)
- wrapped_exports 处理
实际上就是一个装饰器,可以将信息包装起来,方便显示
def wrapper(model):
def wrap(func):
@functools.wraps(func)
def inner(*args, **kwargs):
try:
return func(*args, **kwargs)
except DbtRuntimeError as exc:
exc.add_node(model)
raise exc
return inner
return wrap
def wrapped_exports(model):
wrap = wrapper(model)
return {name: wrap(export) for name, export in CONTEXT_EXPORTS.items()}
说明
exceptions 对于我们可以稳健的模型还是比较方便的,可以尽早失败,dbt 的return 实现了一种尽早返回数据的能力
参考资料
https://docs.getdbt.com/reference/dbt-jinja-functions/exceptions