-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
349bd69
commit 8c73beb
Showing
4 changed files
with
75 additions
and
83 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
from dataclasses import astuple, dataclass | ||
from pathlib import Path | ||
from typing import Callable, TypeVar, Union | ||
from gersemi.exceptions import ASTMismatch, ParsingError | ||
from gersemi.utils import fromfile | ||
|
||
|
||
T = TypeVar("T", covariant=True) | ||
|
||
|
||
@dataclass | ||
class Error: | ||
exception: Exception | ||
path: Path | ||
|
||
|
||
Result = Union[T, Error] | ||
|
||
|
||
def apply(function: Callable[..., T], path: Path, *args, **kwargs) -> Result[T]: | ||
try: | ||
return function(path, *args, **kwargs) | ||
except Exception as exception: # pylint: disable=broad-except | ||
return Error(exception, path) | ||
|
||
|
||
ERROR_MESSAGE_TEMPLATES = { | ||
ASTMismatch: "{path}: AST mismatch after formatting", | ||
ParsingError: "{path}:{exception}", | ||
UnicodeDecodeError: "{path}: file can't be read: {exception}", | ||
} | ||
FALLBACK_ERROR_MESSAGE_TEMPLATE = "{path}: runtime error, {exception}" | ||
|
||
|
||
def get_error_message(error: Error) -> str: | ||
exception, path = astuple(error) | ||
message = FALLBACK_ERROR_MESSAGE_TEMPLATE | ||
for exception_type, template in ERROR_MESSAGE_TEMPLATES.items(): | ||
if isinstance(exception, exception_type): | ||
message = template | ||
break | ||
return message.format(path=fromfile(path), exception=exception) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters