【发布时间】:2020-06-11 01:34:42
【问题描述】:
有没有办法在不使用 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
我已经在 settings.py 中配置了。
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,
'EXCEPTION_HANDLER':'my_project.my_app.exceptions.custom_exception_handler'}
【问题讨论】:
-
您可以编写自己的中间件来处理异常。但是,这并不能处理其他中间件的异常 AFAIU。
-
@Thomas hesse 你能举个例子吗?
-
我确实提供了一个答案,希望它可以帮助你。这确实不是什么新鲜事,但希望对您有所帮助。
标签: django exception django-rest-framework django-rest-viewsets django-errors