__init__.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. """GRASS GIS interface to Python exceptions
  2. """
  3. import subprocess
  4. class DBError(Exception):
  5. pass
  6. class FatalError(Exception):
  7. pass
  8. class FlagError(Exception):
  9. pass
  10. class GrassError(Exception):
  11. pass
  12. class ImplementationError(Exception):
  13. pass
  14. class OpenError(Exception):
  15. pass
  16. class ParameterError(Exception):
  17. pass
  18. class ScriptError(Exception):
  19. """Raised during script execution. ::
  20. >>> error = ScriptError('My error message!')
  21. >>> error.value
  22. 'My error message!'
  23. >>> print(error)
  24. My error message!
  25. """
  26. def __init__(self, value):
  27. self.value = value
  28. def __str__(self):
  29. return self.value
  30. class Usage(Exception):
  31. pass
  32. # TODO: we inherit from subprocess to be aligned with check_call but it is needed?
  33. # perhaps it would be better to inherit from Exception or from ScriptError
  34. class CalledModuleError(subprocess.CalledProcessError):
  35. """Raised when a called module ends with error (non-zero return code)
  36. Used for failures of modules called as subprocesses from Python code.
  37. """
  38. def __init__(self, module, code, returncode, errors=None):
  39. """Create an exception with a full error message based on the parameters.
  40. :param module: module name
  41. :param code: some code snipped which contains parameters
  42. :param returncode: process returncode (assuming non-zero)
  43. :param errors: errors provided by the module (e.g., stderr)
  44. """
  45. # CalledProcessError has undocumented constructor
  46. super(CalledModuleError, self).__init__(returncode, module)
  47. if not module or module in code:
  48. # No need to include module name if it is directly in code
  49. # of if it is not set.
  50. executed = code
  51. else:
  52. # Make sure module name is there if provided and not in code.
  53. executed = f"{module} {code}"
  54. if errors:
  55. # We assume actual errors, e.g., captured stderr.
  56. err = _("See the following errors:\n{errors}").format(errors=errors)
  57. else:
  58. # In command line, the errors will be above, but in testing framework
  59. # or notebooks, the errors will be somewhere else than the traceback.
  60. err = _("See errors above the traceback or in the error output.")
  61. # The full message
  62. self.msg = _(
  63. "Module run `{executed}` ended with an error.\n"
  64. "The subprocess ended with a non-zero return code: {returncode}."
  65. " {see_errors}"
  66. ).format(
  67. executed=executed,
  68. returncode=returncode,
  69. see_errors=err,
  70. )
  71. def __str__(self):
  72. return self.msg