Coverage for common/exceptions.py: 42%

19 statements  

« prev     ^ index     » next       coverage.py v7.8.0, created at 2025-08-27 10:34 -0500

1""" 

2crate_anon/common/exceptions.py 

3 

4=============================================================================== 

5 

6 Copyright (C) 2015, University of Cambridge, Department of Psychiatry. 

7 Created by Rudolf Cardinal (rnc1001@cam.ac.uk). 

8 

9 This file is part of CRATE. 

10 

11 CRATE is free software: you can redistribute it and/or modify 

12 it under the terms of the GNU General Public License as published by 

13 the Free Software Foundation, either version 3 of the License, or 

14 (at your option) any later version. 

15 

16 CRATE is distributed in the hope that it will be useful, 

17 but WITHOUT ANY WARRANTY; without even the implied warranty of 

18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

19 GNU General Public License for more details. 

20 

21 You should have received a copy of the GNU General Public License 

22 along with CRATE. If not, see <https://www.gnu.org/licenses/>. 

23 

24=============================================================================== 

25 

26**Exception-handling functions.** 

27 

28""" 

29 

30import logging 

31import sys 

32import traceback 

33from typing import Callable, NoReturn 

34 

35from crate_anon.common.constants import EXIT_FAILURE, EXIT_SUCCESS 

36 

37log = logging.getLogger(__name__) 

38 

39 

40def report_exception(exc: Exception) -> None: 

41 """ 

42 Prints a critical exception nicely to the log. 

43 

44 Args: 

45 exc: the exception 

46 """ 

47 log.critical(exc) # the exception message 

48 # log.critical(exc, exc_info=True) # message + traceback 

49 traceback_msg = "".join( 

50 traceback.format_exception( 

51 None, exc, exc.__traceback__ # etype: ignored 

52 ) 

53 ) # https://www.python.org/dev/peps/pep-3134/ 

54 log.error(traceback_msg) 

55 

56 

57def call_main_with_exception_reporting(main_function: Callable) -> NoReturn: 

58 try: 

59 result = main_function() 

60 if isinstance(result, int): 

61 sys.exit(result) 

62 else: 

63 sys.exit(EXIT_SUCCESS) 

64 except Exception as exc: 

65 report_exception(exc) 

66 sys.exit(EXIT_FAILURE)