2014-01-08 24 views
1

我有用Django實現的JSON API(作爲項目的一部分)。 有時我會以JSON形式向用戶返回錯誤。我想通過標準錯誤報告程序通過電子郵件通知管理員(例如,當未捕獲的異常提出時)。但是我也想返回一些JSON響應,而不是500錯誤頁面。 一些元代碼,以確保一切都清楚:Django:將錯誤發送給管理員並返回給用戶的響應

def request_handler(request): 
    try: 
     code_that_rises_an_exception() 
     return response('{"result":"success"}') 
    except Exception,e: 
     notify_admin_about_error(e)   # <- this function is required 
     return response('{"result":"error"}') 

謝謝!

+0

我試圖谷歌,但無法找到解決方案。如果我沒有捕獲異常 - 管理員將通過電子郵件通知堆棧跟蹤和大量信息,但同一時間用戶將收到500錯誤,而不是有效的JSON響應。我想統一這兩個階段 - 發送堆棧跟蹤到管理員和對用戶的響應。 – Yarg

+0

你也可以修改500錯誤頁面來返回JSON – maxbellec

回答

1

您可以使用Django Middleware。中間件允許您修改/處理提供給視圖的Django的HttpRequest對象和視圖返回的HttpResponse對象,並在視圖引發異常時採取操作。您可以使用此功能完成各種任務,例如記錄您收到的請求的元數據,錯誤報告等。每當視圖引發異常時,Django都會調用process_exception,並且您可以定義process_exception()以便每當向您發送郵件時會引發異常。

class ErrorReportingMiddleware(object): 
    def process_exception(self, request, exception): 
     send_mail_to_admin(exception) # you can collect some more information here 
     return HttpResponse('{"result":"error"}') # this response is returned to the user 

將此類添加到您的MIDDLEWARE_CLASSES變量中,該變量位於該元組末尾的settings.py中。

你的看法將減少到:

def request_handler(request): 
    code_that_rises_an_exception() 
    return response('{"result":"success"}') 

現在,如果一個異常被request_handler提出,Django的就打電話給你ErrorReportingMiddleware的process_exception方法,將郵件發送給有關異常的管理員,並返回一個JSON響應到瀏覽器而不是500頁。我將實現send_mail_to_admin作爲異步函數,以便由django處理響應不會因發送郵件而被阻止,並且快速響應會返回給用戶。

+0

謝謝你的迴應。這種方式看起來非常複雜。我提出了一個非常簡單的例子,但真正的代碼會非常龐大​​。我希望有一個本地方法來發送信息。但是,如果我找不到它,我會用這樣的東西。 – Yarg

相關問題