【问题标题】:Python: Getting the error message of an exceptionPython:获取异常的错误消息
【发布时间】:2011-05-26 12:43:40
【问题描述】:

在python 2.6.6中,如何捕获异常的错误信息。

IE:

response_dict = {} # contains info to response under a django view.
try:
    plan.save()
    response_dict.update({'plan_id': plan.id})
except IntegrityError, e: #contains my own custom exception raising with custom messages.
    response_dict.update({'error': e})
return HttpResponse(json.dumps(response_dict), mimetype="application/json")

这似乎不起作用。我明白了:

IntegrityError('Conflicts are not allowed.',) is not JSON serializable

【问题讨论】:

  • “这似乎不起作用。” - 它应该做什么和不做什么?
  • 您使用的是哪个版本的 Python?
  • 您好,我已经更新了我的问题。谢谢

标签: python django exception-handling


【解决方案1】:

先通过str()

response_dict.update({'error': str(e)})

另请注意,某些异常类可能具有给出确切错误的特定属性。

【讨论】:

    【解决方案2】:

    关于str 的一切都是正确的,还有另一个答案:Exception 实例具有message 属性,您可能想要使用它(如果您自定义的IntegrityError 没有做一些特别的事情):

    except IntegrityError, e: #contains my own custom exception raising with custom messages.
        response_dict.update({'error': e.message})
    

    【讨论】:

    【解决方案3】:

    如果您要翻译您的应用程序,您应该使用unicode 而不是string

    顺便说一句,如果您因为 Ajax 请求而使用 json,我建议您使用 HttpResponseServerError 而不是 HttpResponse 发回错误:

    from django.http import HttpResponse, HttpResponseServerError
    response_dict = {} # contains info to response under a django view.
    try:
        plan.save()
        response_dict.update({'plan_id': plan.id})
    except IntegrityError, e: #contains my own custom exception raising with custom messages.
        return HttpResponseServerError(unicode(e))
    
    return HttpResponse(json.dumps(response_dict), mimetype="application/json")
    

    然后管理 Ajax 过程中的错误。 如果您希望我可以发布一些示例代码。

    【讨论】:

      【解决方案4】:

      这对我有用:

      def getExceptionMessageFromResponse( oResponse ):
          #
          '''
          exception message is burried in the response object,
          here is my struggle to get it out
          '''
          #
          l = oResponse.__dict__['context']
          #
          oLast = l[-1]
          #
          dLast = oLast.dicts[-1]
          #
          return dLast.get( 'exception' )
      

      【讨论】:

        【解决方案5】:

        假设你提出这样的错误

        raise someError("some error message")
        

        并且'e'被捕获错误实例

        str(e) 返回:

        [ErrorDetail(string='some error message', code='invalid')]
        

        但如果你只想要“一些错误信息”

        e.detail
        

        会给你(实际上给你一个 str 列表,其中包括“一些错误消息”)

        【讨论】:

          猜你喜欢
          • 2012-10-08
          • 2014-08-11
          • 2011-06-09
          • 2019-02-22
          • 2014-06-14
          • 2017-02-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多