【问题标题】:TastyPie Custom error and status code = 500 with debug = TrueTastyPie 自定义错误和状态代码 = 500,调试 = True
【发布时间】:2017-03-10 08:21:17
【问题描述】:

我试图在我的 api.py 文件中使用 DEBUG = True 引发自定义错误。它抛出错误

{
"error_message": "Sorry, this request could not be processed. Please try again later."
}

这是默认的 TASTYPIE_CANNED_ERROR 消息。

我希望错误是这样的:

{"error_message": "{'id': 2671, 'error': 'Duplicate'}"}

我尝试覆盖 _handle_500 方法,但这似乎返回了我的网站 html 页面作为响应。

我得到了状态码为 400 的所需格式:

raise BadRequest({"id": int(attempt[0].id), "error": "Duplicate"})

但我需要状态码为 500。

【问题讨论】:

    标签: django tastypie custom-error-handling


    【解决方案1】:

    使用 ImmediateHttpResponse 并创建错误消息字典,然后将其作为响应发送。而且还需要指定content_type="application/json"。

    from django.http import HttpResponse
    from tastypie.exceptions import ImmediateHttpResponse
    
    // Build your response
    response = {"error_message": {'id': 2671, 'error': 'Duplicate'}}
    
    raise ImmediateHttpResponse(response=HttpResponse(json.dumps(response), status=401, content_type="application/json"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-07
      • 1970-01-01
      • 2013-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多