簡體   English   中英

Django REST自定義錯誤

[英]Django REST Custom Errors

我正在嘗試從REST Django框架創建自定義錯誤響應。

我在views.py中包含了以下內容,

from rest_framework.views import exception_handler

def custom_exception_handler(exc):
    """
    Custom exception handler for Django Rest Framework that adds
    the `status_code` to the response and renames the `detail` key to `error`.
    """
    response = exception_handler(exc)

    if response is not None:
        response.data['status_code'] = response.status_code
        response.data['error'] = response.data['detail']
        response.data['detail'] = "CUSTOM ERROR"

    return response

並且還將以下內容添加到settings.py中

REST_FRAMEWORK = {
              'DEFAULT_PERMISSION_CLASSES': (
                  'rest_framework.permissions.AllowAny',
              ),
              'EXCEPTION_HANDLER': 'project.input.utils.custom_exception_handler'
        }

我錯過了什么,因為我沒有得到預期的回應。 即400 API響應中的自定義錯誤消息。

謝謝,

正如Bibhas所說,使用自定義異常處理程序,您只能在調用異常時返回自己定義的錯誤。 如果要在不觸發異常的情況下返回自定義響應錯誤,則需要在視圖本身中返回它。 例如:

    return Response({'detail' : "Invalid arguments", 'args' : ['arg1', 'arg2']}, 
                     status = status.HTTP_400_BAD_REQUEST)

文檔 -

請注意,只會針對由引發的異常生成的響應調用異常處理程序。 它不會用於視圖直接返回的任何響應,例如序列化程序驗證失敗時通用視圖返回的HTTP_400_BAD_REQUEST響應。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM