![](/img/trans.png)
[英]How can I manually trigger/start celery tasks in a django application?
[英]How can I trigger a 500 error in Django?
我正在嘗試設置電子郵件錯誤日志,我想對其進行測試。
在 Django 中觸發 500 錯誤的簡單方法是什么? 令人驚訝的是,這里尚未討論這一點。
像這樣的測試視圖將起作用:
from django.http import HttpResponse
def my_test_500_view(request):
# Return an "Internal Server Error" 500 response code.
return HttpResponse(status=500)
或使用烘焙錯誤類:
from django.http import HttpResponseServerError
def my_test_500_view(request):
# Return an "Internal Server Error" 500 response code.
return HttpResponseServerError()
引發適當的Exception
是測試這一點的最可靠的方法。 返回任何種類的HttpResponse
,如@agconti 的回答,將不允許您測試錯誤處理的行為。 你只會看到一個空白頁。 引發異常會觸發正確的響應代碼和您期望的“真實”錯誤的內部 Django 行為。
響應代碼 500 表示服務器不知道該做什么。 最簡單的方法是寫入您的測試或測試視圖raise Exception('Make response code 500!')
。
大多數其他錯誤應該與旨在觸發特定響應代碼的異常一起引發。 這是您可能引發的 Django 異常的完整列表。
老問題,但我希望這對將來的人有所幫助。 接受的答案並沒有真正回答原始問題......您可以通過引發 ApiException 使用 django rest 框架輕松做到這一點:
from rest_framework.exceptions import APIException
try:
...
except ...:
raise ApiException('custom exception message')
這將從您的視圖中返回狀態為 500 的響應。 如果您從 API 調用另一個函數並且不想管理來自該函數的返回值來決定是否返回狀態為 500 的響應,則非常有用。您可以像這樣使用它:
raise ApiException
默認響應消息(在撰寫本文時)將是“發生服務器錯誤。”。
有一些預定義的 ApiException 子類會引發不同類型的錯誤,請檢查文件 rest_framework.exceptions,如果您需要一個不在那里的,您可以像這樣擴展 ApiException:
from rest_framework.exceptions import APIException
class YourCustomApiExceptionName(APIException):
def __init__(self, status, detail):
self.status_code = status
self.detail = detail
用法:
raise YourCustomApiExceptionName(100, 'continue')
您還可以定義自定義狀態和詳細信息,但在大多數情況下沒有多大意義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.