How to return Python exception info to jQuery.ajax POST call?
Question: I make a JQUERY AJAX code in my HTML code:

    
    
    $.ajax({
                    type: "POST",
                    url:  "runrep.py",
                    data:
                    {
                           'my_data' : 'test' 
                    },
                    success: function(html)
                    {
                    }
                    error:function(xhr,err)
                    {
                         alert("Failed\nreadyState: "+xhr.readyState+"\nstatus: "+xhr.status + "\nresponseText: "+xhr.responseText);
                    }
    });
    

In my backend code 'runrep.py' I have specifically trying to connect to a
MySQL DB which is down.

When I run the program in Apache error_logs I see the DB unable to connect
MySQL exception but the UI page does not renders any error?

    
    
    class SampleClass:
            def __init__(self):
                    self.conn = MySQLdb.connect(host="host",user="user",passwd="passwd",db="db")
                    self.cursor = self.conn.cursor(MySQLdb.cursors.DictCursor)
                    form = cgi.FieldStorage()
                    self.my_data = form["my_data"].value
    

What should I do that I can print the program fault either be it exceptions,
errors due to run time issue to browser / client side? Even if I catch the
exceptions how can I return failure to AJAX call accordingly?


Answer: Basically, you should handle the exception in your code and pass it to the
server code. For example, if you are using Werkzeug/Flask (see [the
documentation](http://werkzeug.pocoo.org/docs/exceptions/)), you can do it
this way:

    
    
    import werkzeug
    
    class SampleClass:
        def __init__(self):
            try:
                self.conn = MySQLdb.connect(host="host",user="user",passwd="passwd",db="db")
            except Exception as e:
                raise werkzeug.exceptions.HTTPException("Error: %s" % str(e) )
    
            self.cursor = self.conn.cursor(MySQLdb.cursors.DictCursor)
            form = cgi.FieldStorage()
            self.starttime = form["my_data"].value
    

The raised exception should be converted by the server framework to a proper
HTTP response with some HTTP status code representing an error, such as 500.
When an erroneous code is responded by the server, then you can handle it in
the AJAX query.

Refer to your HTTP/WSGI framework for more information about exception
handling and responses with error status codes.

