如何将Python异常信息返回给jQuery.ajax POST调用?

时间:2012-06-01 09:34:13

标签: jquery python ajax

我在HTML代码中制作了一个JQUERY AJAX代码:

$.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);
                }
});

在我的后端代码'runrep.py'中,我特意尝试连接到已关闭的MySQL数据库。

当我在Apache error_logs中运行程序时,我看到数据库无法连接MySQL异常但是UI页面没有呈现任何错误?

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

我应该怎么做才能打印程序错误,不管是因为运行时问题导致浏览器/客户端错误吗?即使我抓住异常,我怎么能相应地返回AJAX调用失败?

1 个答案:

答案 0 :(得分:0)

基本上,您应该在代码中处理异常并将其传递给服务器代码。例如,如果您使用的是Werkzeug / Flask(请参阅the documentation),您可以这样做:

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

服务器框架应该将引发的异常转换为正确的HTTP响应,其中一些HTTP状态代码表示错误,例如500.当服务器响应错误的代码时,您可以在AJAX查询中处理它

有关异常处理和带错误状态代码的响应的详细信息,请参阅HTTP / WSGI框架。

相关问题