annif.exception   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 72
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 33
dl 0
loc 72
rs 10
c 0
b 0
f 0
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A AnnifException.__init__() 0 12 2
A AnnifException.format_message() 0 10 3
1
"""Custom exceptions used by Annif"""
2
3
from __future__ import annotations
4
5
from click import ClickException
6
7
8
class AnnifException(ClickException):
9
    """Base Annif exception. We define this as a subclass of ClickException so
10
    that the CLI can automatically handle exceptions. This exception cannot be
11
    instantiated directly - subclasses should be used instead."""
12
13
    def __init__(
14
        self,
15
        message: str,
16
        project_id: str | None = None,
17
        backend_id: str | None = None,
18
    ) -> None:
19
        super().__init__(message)
20
        self.project_id = project_id
21
        self.backend_id = backend_id
22
23
        if self.prefix is None:
24
            raise TypeError("Cannot instantiate exception without a prefix.")
25
26
    # subclasses should set this to a descriptive prefix
27
    prefix = None
28
29
    def format_message(self) -> str:
30
        if self.project_id is not None:
31
            return "{} project '{}': {}".format(
32
                self.prefix, self.project_id, self.message
33
            )
34
        if self.backend_id is not None:
35
            return "{} backend '{}': {}".format(
36
                self.prefix, self.backend_id, self.message
37
            )
38
        return "{}: {}".format(self.prefix, self.message)
39
40
41
class NotInitializedException(AnnifException):
42
    """Exception raised for attempting to use a project or backend that
43
    cannot be initialized, most likely since it is not yet functional
44
    because of lack of vocabulary or training."""
45
46
    prefix = "Couldn't initialize"
47
48
49
class ConfigurationException(AnnifException):
50
    """Exception raised when a project or backend is misconfigured."""
51
52
    prefix = "Misconfigured"
53
54
55
class NotEnabledException(AnnifException):
56
    """Exception raised when an operation is not enabled."""
57
58
    prefix = "Not enabled"
59
60
61
class NotSupportedException(AnnifException):
62
    """Exception raised when an operation is not supported by a project or
63
    backend."""
64
65
    prefix = "Not supported"
66
67
68
class OperationFailedException(AnnifException):
69
    """Exception raised when an operation fails for some unknown reason."""
70
71
    prefix = "Operation failed"
72