Catching a jira-python exception

arynhard picture arynhard · Aug 22, 2013 · Viewed 9.2k times · Source

I am trying to handle jira-python exception but my try, except does not seem to catch it. I also need to add more lines in order to be able to post this. So there they are, the lines.

try:
    new_issue = jira.create_issue(fields=issue_dict)
    stdout.write(str(new_issue.id))
except jira.exceptions.JIRAError:
    stdout.write("JIRAError")
    exit(1)

Here is the code that raises the exception:

import json


class JIRAError(Exception):
    """General error raised for all problems in operation of the client."""
    def __init__(self, status_code=None, text=None, url=None):
        self.status_code = status_code
        self.text = text
        self.url = url

    def __str__(self):
        if self.text:
            return 'HTTP {0}: "{1}"\n{2}'.format(self.status_code, self.text, self.url)
        else:
            return 'HTTP {0}: {1}'.format(self.status_code, self.url)


def raise_on_error(r):
    if r.status_code >= 400:
        error = ''
        if r.text:
            try:
                response = json.loads(r.text)
                if 'message' in response:
                    # JIRA 5.1 errors
                    error = response['message']
                elif 'errorMessages' in response and len(response['errorMessages']) > 0:
                    # JIRA 5.0.x error messages sometimes come wrapped in this array
                    # Sometimes this is present but empty
                    errorMessages = response['errorMessages']
                    if isinstance(errorMessages, (list, tuple)):
                        error = errorMessages[0]
                    else:
                        error = errorMessages
                elif 'errors' in response and len(response['errors']) > 0:
                    # JIRA 6.x error messages are found in this array.
                    error = response['errors']
                else:
                    error = r.text
            except ValueError:
                error = r.text
        raise JIRAError(r.status_code, error, r.url)

Answer

user110954 picture user110954 · Aug 19, 2016

I know I'm not answering the question, but I feel I need to warn people that could get confused by that code (as I did)... Maybe you are trying to write your own version of jira-python or it's an old version?

In any case, here the link to the jira-python code for the JIRAError class and here the list of codes

to catch the exception from that package I use the below code

from jira import JIRA, JIRAError
try:
   ...
except JIRAError as e:
   print e.status_code, e.text