Skip to content

Commit

Permalink
raise exception from previously raised exc to keep stack trace
Browse files Browse the repository at this point in the history
  • Loading branch information
ssssarah committed Oct 30, 2023
1 parent 604eed6 commit a9cfbdd
Show file tree
Hide file tree
Showing 18 changed files with 120 additions and 101 deletions.
4 changes: 2 additions & 2 deletions kgforge/core/archetypes/mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,9 @@ def load_file(cls, filepath, raise_ex=True):

raise OSError

except OSError:
except OSError as e:
if raise_ex:
raise FileNotFoundError
raise FileNotFoundError from e
return None

@classmethod
Expand Down
4 changes: 2 additions & 2 deletions kgforge/core/commons/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ def __init__(self, document: Union[Dict, List, str], iri: Optional[str] = None)
elif isinstance(document, str):
try:
self.document = source_to_json(document)
except Exception:
raise ValueError("context not resolvable")
except Exception as e:
raise ValueError("context not resolvable") from e
elif isinstance(document, Dict):
self.document = document if "@context" in document else {"@context": document}
self.iri = iri
Expand Down
22 changes: 13 additions & 9 deletions kgforge/core/commons/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,37 +40,41 @@ class ResolvingError(Exception):
# Store operations.


class RegistrationError(Exception):
class RunException(Exception):
pass


class UploadingError(Exception):
class RegistrationError(RunException):
pass


class RetrievalError(Exception):
class UploadingError(RunException):
pass


class DownloadingError(Exception):
class RetrievalError(RunException):
pass


class UpdatingError(Exception):
class DownloadingError(RunException):
pass


class TaggingError(Exception):
class UpdatingError(RunException):
pass


class DeprecationError(Exception):
class TaggingError(RunException):
pass


class QueryingError(Exception):
class DeprecationError(RunException):
pass


class FreezingError(Exception):
class QueryingError(RunException):
pass


class FreezingError(RunException):
pass
10 changes: 5 additions & 5 deletions kgforge/core/commons/execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@
import inspect
import traceback
from functools import wraps
from typing import Any, Callable, List, Optional, Tuple, Union
from typing import Any, Callable, List, Optional, Tuple, Union, Type

from kgforge.core.resource import Resource
from kgforge.core.commons.actions import (Action, Actions, collect_lazy_actions,
execute_lazy_actions)
from kgforge.core.commons.exceptions import NotSupportedError
from kgforge.core.commons.exceptions import NotSupportedError, RunException


# POLICY Should have only one function called 'wrapper'. See catch().
Expand Down Expand Up @@ -98,7 +98,7 @@ def dispatch(data: Union[Resource, List[Resource]], fun_many: Callable,


def run(fun_one: Callable, fun_many: Optional[Callable], data: Union[Resource, List[Resource]],
exception: Callable, id_required: bool = False,
exception: Type[RunException], id_required: bool = False,
required_synchronized: Optional[bool] = None, execute_actions: bool = False,
monitored_status: Optional[str] = None, catch_exceptions: bool = True, **kwargs) -> None:
# POLICY Should be called for operations on resources where recovering from errors is needed.
Expand All @@ -124,7 +124,7 @@ def _run_many(fun: Callable, resources: List[Resource], *args, **kwargs) -> None
_run_one(fun, x, *args, **kwargs)


def _run_one(fun: Callable, resource: Resource, exception: Callable, id_required: bool,
def _run_one(fun: Callable, resource: Resource, exception: Type[RunException], id_required: bool,
required_synchronized: Optional[bool], execute_actions: bool,
monitored_status: Optional[str], catch_exceptions: bool, **kwargs) -> None:
try:
Expand Down Expand Up @@ -155,7 +155,7 @@ def _run_one(fun: Callable, resource: Resource, exception: Callable, id_required
if monitored_status:
setattr(resource, monitored_status, status)

resource._last_action = Action(fun.__name__, succeeded, exception)
resource.set_last_action(Action(fun.__name__, succeeded, exception))

if not catch_exceptions and exception:
raise exception
5 changes: 4 additions & 1 deletion kgforge/core/commons/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,10 @@ def load_file_as_byte(source: str):
response.raise_for_status()
data = response.content
except RequestException as re:
raise AttributeError(f"Failed to load the configuration from {source}. The provided source is not a valid file path or URL: {str(re)}")
raise AttributeError(
f"Failed to load the configuration from {source}. "
f"The provided source is not a valid file path or URL: {str(re)}"
) from re
return data


Expand Down
9 changes: 5 additions & 4 deletions kgforge/core/commons/imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,10 @@ def import_class(configuration: str, forge_module_name: str) -> Callable:
class_name, module_import = matched.groups(default=forge_module_import)
module = import_module(module_import)
return getattr(module, class_name)
except ModuleNotFoundError:
raise ConfigurationError(f"{archetype} module not found for '{configuration}'")
except AttributeError:
raise ConfigurationError(f"{archetype} class not found for '{configuration}'")
except ModuleNotFoundError as exc1:
raise ConfigurationError(f"{archetype} module not found for '{configuration}'") from \
exc1
except AttributeError as exc2:
raise ConfigurationError(f"{archetype} class not found for '{configuration}'") from exc2
else:
raise ConfigurationError(f"incorrect {archetype} configuration for '{configuration}'")
5 changes: 4 additions & 1 deletion kgforge/core/commons/sparql_query_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,10 @@ def build(
f"FILTER(?v{index} {sparql_operator_map[f.operator]} {_box_value_as_full_iri(value)})"
)
except NotImplementedError as nie:
raise ValueError(f"Operator '{sparql_operator_map[f.operator]}' is not supported with the value '{f.value}': {str(nie)}")
raise ValueError(
f"Operator '{sparql_operator_map[f.operator]}' "
f"is not supported with the value '{f.value}': {str(nie)}"
) from nie
return statements, sparql_filters

@staticmethod
Expand Down
28 changes: 14 additions & 14 deletions kgforge/core/conversions/rdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

from copy import deepcopy

from typing import Union, Dict, List, Tuple, Optional, Callable, Any
from typing import Union, Dict, List, Tuple, Optional, Callable

from enum import Enum
import json
Expand Down Expand Up @@ -69,9 +69,9 @@ def as_jsonld(
) -> Union[Dict, List[Dict]]:
try:
valid_form = Form(form.lower())
except ValueError:
except ValueError as e:
supported_forms = tuple(item.value for item in Form)
raise NotSupportedError(f"supported serialization forms are {supported_forms}")
raise NotSupportedError(f"supported serialization forms are {supported_forms}") from e

return dispatch(
data,
Expand Down Expand Up @@ -163,12 +163,12 @@ def _from_jsonld_one(data: Dict) -> Resource:
if "@context" in data:
try:
resolved_context = Context(data["@context"])
except URLError:
raise ValueError("context not resolvable")
else:
return _remove_ld_keys(data, resolved_context)
else:
raise NotImplementedError("not implemented yet (expanded json-ld)")
except URLError as e:
raise ValueError("context not resolvable") from e

return _remove_ld_keys(data, resolved_context)

raise NotImplementedError("not implemented yet (expanded json-ld)")


def _as_jsonld_many(
Expand Down Expand Up @@ -225,7 +225,7 @@ def _as_jsonld_one(
resource, store_metadata, context, metadata_context
)
except Exception as e:
raise ValueError(e)
raise ValueError(e) from e

if store_metadata is True and len(metadata_graph) > 0:
metadata_expanded = json.loads(metadata_graph.serialize(format="json-ld"))
Expand Down Expand Up @@ -335,8 +335,8 @@ def _dicts_to_graph(
metadata["@context"] = metadata_context.document["@context"]
try:
meta_data_graph.parse(data=json.dumps(metadata), format="json-ld")
except Exception:
raise ValueError("generated an invalid json-ld")
except Exception as e:
raise ValueError("generated an invalid json-ld") from e
return graph, meta_data_graph


Expand Down Expand Up @@ -380,8 +380,8 @@ def _resource_context(
except (HTTPError, URLError, NotSupportedError):
try:
context = Context(resource.context, iri)
except URLError:
raise ValueError(f"{resource.context} is not resolvable")
except URLError as e:
raise ValueError(f"{resource.context} is not resolvable") from e
else:
context = model_context

Expand Down
6 changes: 3 additions & 3 deletions kgforge/core/forge.py
Original file line number Diff line number Diff line change
Expand Up @@ -441,12 +441,12 @@ def resolve(
if isinstance(strategy, ResolvingStrategy)
else ResolvingStrategy[strategy]
)
except Exception:
except Exception as e:
raise AttributeError(
f"Invalid ResolvingStrategy value '{strategy}'. "
f"Allowed names are {[name for name, member in ResolvingStrategy.__members__.items()]} "
f"and allowed members are {[member for name, member in ResolvingStrategy.__members__.items()]}"
)
) from e
return rov.resolve(
text,
target,
Expand Down Expand Up @@ -491,7 +491,7 @@ def format(self, what: str = None, *args, formatter: Union[Formatter, str] = For
f"Invalid Formatter value '{formatter}'. "
f"Allowed names are {[name for name, member in Formatter.__members__.items()]} "
f"and allowed members are {[member for name, member in Formatter.__members__.items()]}"
)
) from e

if formatter == Formatter.STR:
if what is None:
Expand Down
4 changes: 3 additions & 1 deletion kgforge/core/reshaping.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,4 +99,6 @@ def _collect(things: List) -> Iterator[str]:
prepared = jsoned if isinstance(jsoned, List) else [jsoned]
return list(_collect(prepared))
except Exception as e:
raise exception(f"An error occur when collecting values for path to follow '{follow}': {str(e)}")
raise exception(
f"An error occur when collecting values for path to follow '{follow}': {str(e)}"
) from e
4 changes: 2 additions & 2 deletions kgforge/core/wrappings/paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,10 @@ def __init__(self, path: List[str], operator: Union[str, FilterOperator], value:
try:
self.operator: str = operator.value if isinstance(operator, FilterOperator) \
else FilterOperator(operator).value
except Exception:
except Exception as e:
raise ValueError(
f"Invalid operator value '{operator}'. Allowed operators are {[member.value for name, member in FilterOperator.__members__.items()]}"
)
) from e
self.value: Any = value

def __eq__(self, other):
Expand Down
2 changes: 1 addition & 1 deletion kgforge/specializations/models/rdf/directory_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def resolve_context(self, iri: str) -> Dict:
try:
context = Context(iri)
except FileNotFoundError as e:
raise ValueError(e)
raise ValueError(e) from e

self._context_cache.update({iri: context.document})
return context.document
Expand Down
10 changes: 6 additions & 4 deletions kgforge/specializations/models/rdf/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,14 +158,16 @@ def materialize(self, iri: URIRef) -> NodeProperties:
def validate(self, resource: Resource, type_: str):
try:
if isinstance(resource.type, list) and type_ is None:
raise ValueError("Resource has list of types as attribute and type_ parameter is not specified. "
"Please provide a type_ parameter to validate against it.")
raise ValueError(
"Resource has list of types as attribute and type_ parameter is not specified. "
"Please provide a type_ parameter to validate against it."
)
if type_ is None:
shape_iri = self.types_to_shapes[resource.type]
else:
shape_iri = self.types_to_shapes[type_]
except AttributeError:
raise TypeError("resource requires a type attribute")
except AttributeError as exc:
raise TypeError("Resource requires a type attribute") from exc

data_graph = as_graph(resource, False, self.context, None, None)
return self._validate(shape_iri, data_graph)
Expand Down
8 changes: 4 additions & 4 deletions kgforge/specializations/models/rdf_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,8 @@ def _generate_context(self) -> Context:
def _template(self, type: str, only_required: bool) -> Dict:
try:
uri = self.service.types_to_shapes[type]
except KeyError:
raise ValueError("type '" + type + "' not found in " + self.source)
except KeyError as exc:
raise ValueError("type '" + type + "' not found in " + self.source) from exc
node_properties = self.service.materialize(uri)
dictionary = parse_attributes(node_properties, only_required, None)
return dictionary
Expand All @@ -105,8 +105,8 @@ def schema_id(self, type: str) -> str:
try:
shape_iri = self.service.types_to_shapes[type]
return str(self.service.schema_source_id(shape_iri))
except KeyError:
raise ValueError("type not found")
except KeyError as exc:
raise ValueError("type not found") from exc

def validate(self, data: Union[Resource, List[Resource]], execute_actions_before: bool, type_: str) -> None:
run(self._validate_one, self._validate_many, data, execute_actions=execute_actions_before,
Expand Down
11 changes: 7 additions & 4 deletions kgforge/specializations/resources/datasets.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,10 +103,13 @@ def _add_prov_property(self, resource, prov_type, reference_property, reference_
reference = self._forge.reshape(resource, keep, versioned)
except AttributeError as ae:
if '_rev' in str(ae) and versioned:
raise ValueError(f"Missing resource revision value to build a versioned ({versioned}) reference. "
f"Provide a revision number to the resource (by registering it for example) or set 'versioned' argument to False if no versioned reference is needed.")
else:
raise ae
raise ValueError(
f"Missing resource revision value to build a versioned ({versioned}) reference. "
f"Provide a revision number to the resource (by registering it for example) "
f"or set 'versioned' argument to False if no versioned reference is needed."
) from ae

raise ae

result = Resource(type=prov_type, **kwargs)
result.__setattr__(reference_property, reference)
Expand Down
Loading

0 comments on commit a9cfbdd

Please sign in to comment.