小编Shu*_*mar的帖子

Django-rest-framework 中的全局异常处理

有没有一种方法可以在不使用 django rest 框架中的 try-except 块的情况下全局处理所有异常。

我想将 django 抛出的 html 错误页面转换为自定义的 json 对象响应。

我在我的应用程序中创建了一个 exception.py 文件

def custom_exception_handler(exc, context=None):
    response = exception_handler(exc)


    if isinstance(exc, HttpResponseServerError):  
        custom_response_data = { 
            'detail': 'Internal Server Error' # custom exception message
        }
        response.data = custom_response_data

    return response
Run Code Online (Sandbox Code Playgroud)

我已经在 settings.py 中配置了这个。

REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,
'EXCEPTION_HANDLER':'my_project.my_app.exceptions.custom_exception_handler'}
Run Code Online (Sandbox Code Playgroud)

django exception django-errors django-rest-framework django-rest-viewsets

5
推荐指数
2
解决办法
5951
查看次数