Skip to content
Snippets Groups Projects
Commit 4c33cba7 authored by Piotr Maślanka's avatar Piotr Maślanka
Browse files

add CustomException

parent 5e124583
No related branches found
No related tags found
No related merge requests found
# v2.4.29 # v2.4.29
* _TBA_ * added `CustomException`
# v2.4.28 # v2.4.28
......
Exceptions
==========
CustomException
---------------
This is the class you can base your exceptions off. It provides
a reasonable __repr__ and __str__, eg.:
::
class MyException(CustomException):
...
assert str(MyException) == 'MyException()'
__repr__ will additionally prefix the exception class name with entire module path to it.
...@@ -24,6 +24,7 @@ Visit the project's page at GitHub_! ...@@ -24,6 +24,7 @@ Visit the project's page at GitHub_!
import import
files files
time time
exceptions
Indices and tables Indices and tables
......
__version__ = '2.4.29a1' __version__ = '2.4.29'
__all__ = ['BaseSatellaException', 'ResourceLockingError', 'ResourceNotLocked', 'ResourceLocked', import warnings
__all__ = ['BaseSatellaError', 'ResourceLockingError', 'ResourceNotLocked', 'ResourceLocked',
'ConfigurationValidationError', 'ConfigurationError', 'ConfigurationSchemaError', 'ConfigurationValidationError', 'ConfigurationError', 'ConfigurationSchemaError',
'PreconditionError', 'MetricAlreadyExists'] 'PreconditionError', 'MetricAlreadyExists', 'BaseSatellaException', 'CustomException']
class BaseSatellaException(Exception): class CustomException(Exception):
""""Base class for all Satella exceptions""" """"
def __init__(self, msg, *args, **kwargs): Base class for your custom exceptions. It will:
super().__init__(*(msg, *args))
1. Accept any number of arguments
2. Provide faithful __repr__ and a reasonable __str__
It passed all arguments that your exception received via super()
"""
def __init__(self, *args, **kwargs):
super().__init__(*args)
self.kwargs = kwargs self.kwargs = kwargs
self.msg = msg
def __str__(self): def __str__(self) -> str:
a = '%s(%s' % (self.__class__.__qualname__, self.args) a = '%s(%s' % (self.__class__.__qualname__.split('.')[-1], ', '.join(map(repr, self.args)))
if self.kwargs: if self.kwargs:
a += ', '+(', '.join(map(lambda k, v: '%s=%s' % (k, repr(v)), self.kwargs.items()))) a += ', ' + ', '.join(map(lambda k, v: '%s=%s' % (k, repr(v)), self.kwargs.items()))
a += ')' a += ')'
return a return a
def __repr__(self): def __repr__(self) -> str:
a = '%s%s(%s' % ((self.__class__.__module__ + '.') a = '%s%s(%s' % ((self.__class__.__module__ + '.')
if self.__class__.__module__ != 'builtins' else '', if self.__class__.__module__ != 'builtins' else '',
self.__class__.__qualname__, self.__class__.__qualname__,
...@@ -25,11 +33,21 @@ class BaseSatellaException(Exception): ...@@ -25,11 +33,21 @@ class BaseSatellaException(Exception):
if self.kwargs: if self.kwargs:
a += ', ' + (', '.join(map(lambda kv: '%s=%s' % (kv[0], repr(kv[1])), a += ', ' + (', '.join(map(lambda kv: '%s=%s' % (kv[0], repr(kv[1])),
self.kwargs.items()))) self.kwargs.items())))
a += ')' a += ')'
return a return a
class ResourceLockingError(BaseSatellaException): class BaseSatellaError(CustomException):
""""Base class for all Satella exceptions"""
class BaseSatellaException(BaseSatellaError):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
warnings.warn('Use BaseSatellaError instead', DeprecationWarning)
class ResourceLockingError(BaseSatellaError):
"""Base class for resource locking issues""" """Base class for resource locking issues"""
...@@ -41,13 +59,13 @@ class ResourceNotLocked(ResourceLockingError): ...@@ -41,13 +59,13 @@ class ResourceNotLocked(ResourceLockingError):
"""Locking given resource is needed in order to access it""" """Locking given resource is needed in order to access it"""
class PreconditionError(BaseSatellaException, ValueError): class PreconditionError(BaseSatellaError, ValueError):
""" """
A precondition was not met for the argument A precondition was not met for the argument
""" """
class ConfigurationError(BaseSatellaException): class ConfigurationError(BaseSatellaError):
"""A generic error during configuration""" """A generic error during configuration"""
...@@ -66,7 +84,7 @@ class ConfigurationValidationError(ConfigurationSchemaError): ...@@ -66,7 +84,7 @@ class ConfigurationValidationError(ConfigurationSchemaError):
self.value = value self.value = value
class MetricAlreadyExists(BaseSatellaException): class MetricAlreadyExists(BaseSatellaError):
"""Metric with given name already exists, but with a different type""" """Metric with given name already exists, but with a different type"""
def __init__(self, msg, name, requested_type, existing_type): def __init__(self, msg, name, requested_type, existing_type):
......
import unittest import unittest
from satella.exceptions import BaseSatellaException
from satella.exceptions import BaseSatellaError, CustomException
class TestExceptions(unittest.TestCase): class TestExceptions(unittest.TestCase):
def test_exception_kwargs(self): def test_exception_kwargs(self):
e = BaseSatellaException('hello world', label='value') e = BaseSatellaError('hello world', label='value')
self.assertIn("label='value'", repr(e)) self.assertIn("label='value'", repr(e))
def test_exception(self):
try:
raise BaseSatellaException('message', 'arg1', 'arg2')
except BaseSatellaException as e:
self.assertIn('arg1', str(e))
self.assertIn('arg2', str(e))
self.assertIn('BaseSatellaException', str(e))
else:
self.fail()
def test_except_inherited(self): def test_except_inherited(self):
class InheritedException(BaseSatellaException): class InheritedError(CustomException):
pass pass
try: try:
raise InheritedException('message', 'arg1', 'arg2') raise InheritedError('message', 'arg1', 'arg2')
except BaseSatellaException as e: except CustomException as e:
self.assertIn('arg1', str(e)) self.assertEqual(str(e), "InheritedError('message', 'arg1', 'arg2')")
self.assertIn('arg2', str(e))
self.assertIn('InheritedException', str(e))
else: else:
self.fail() self.fail()
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment