本文整理汇总了Python中rest_framework.views.exception_handler方法的典型用法代码示例。如果您正苦于以下问题:Python views.exception_handler方法的具体用法?Python views.exception_handler怎么用?Python views.exception_handler使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rest_framework.views
的用法示例。
在下文中一共展示了views.exception_handler方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: custom_exception_handler
# 需要导入模块: from rest_framework import views [as 别名]
# 或者: from rest_framework.views import exception_handler [as 别名]
def custom_exception_handler(exc, context):
# give more context on the error since DRF masks it as Not Found
if isinstance(exc, Http404):
set_rollback()
return Response(str(exc), status=status.HTTP_404_NOT_FOUND)
# Call REST framework's default exception handler after specific 404 handling,
# to get the standard error response.
response = exception_handler(exc, context)
# No response means DRF couldn't handle it
# Output a generic 500 in a JSON format
if response is None:
logging.exception('Uncaught Exception', exc_info=exc)
set_rollback()
return Response({'detail': 'Server Error'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
# log a few different types of exception instead of using APIException
if isinstance(exc, (DeisException, ServiceUnavailable, HealthcheckException)):
logging.exception(exc.__cause__, exc_info=exc)
return response
示例2: resolwe_exception_handler
# 需要导入模块: from rest_framework import views [as 别名]
# 或者: from rest_framework.views import exception_handler [as 别名]
def resolwe_exception_handler(exc, context):
"""Handle exceptions raised in API and make them nicer.
To enable this, you have to add it to the settings:
.. code:: python
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'resolwe.flow.utils.exceptions.resolwe_exception_handler',
}
"""
response = exception_handler(exc, context)
if isinstance(exc, ValidationError):
if response is None:
response = Response({})
response.status_code = 400
response.data["error"] = exc.message
return response
示例3: core_exception_handler
# 需要导入模块: from rest_framework import views [as 别名]
# 或者: from rest_framework.views import exception_handler [as 别名]
def core_exception_handler(exc, context):
# If an exception is thrown that we don't explicitly handle here, we want
# to delegate to the default exception handler offered by DRF. If we do
# handle this exception type, we will still want access to the response
# generated by DRF, so we get that response up front.
response = exception_handler(exc, context)
handlers = {
'NotFound': _handle_not_found_error,
'ValidationError': _handle_generic_error
}
# This is how we identify the type of the current exception. We will use
# this in a moment to see whether we should handle this exception or let
# Django REST Framework do it's thing.
exception_class = exc.__class__.__name__
if exception_class in handlers:
# If this exception is one that we can handle, handle it. Otherwise,
# return the response generated earlier by the default exception
# handler.
return handlers[exception_class](exc, context, response)
return response
示例4: custom_exception_handler
# 需要导入模块: from rest_framework import views [as 别名]
# 或者: from rest_framework.views import exception_handler [as 别名]
def custom_exception_handler(exc, context):
"""Create custom response for exceptions."""
response = exception_handler(exc, context)
# Now add the HTTP status code to the response.
if response is not None:
errors = []
data = copy.deepcopy(response.data)
if isinstance(data, dict):
errors += _generate_errors_from_dict(data, **{"status_code": response.status_code})
elif isinstance(data, list):
errors += _generate_errors_from_list(data, **{"status_code": response.status_code})
error_response = {"errors": errors}
response.data = error_response
return response
示例5: custom_exception_handler
# 需要导入模块: from rest_framework import views [as 别名]
# 或者: from rest_framework.views import exception_handler [as 别名]
def custom_exception_handler(exc, context):
# Call REST framework's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, context)
# Now add the HTTP status code to the response.
if not response:
if isinstance(exc, (SafeServiceException, SafeCreationServiceException, TransactionServiceException,
FundingServiceException)):
response = Response(status=status.HTTP_422_UNPROCESSABLE_ENTITY)
else:
response = Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)
if str(exc):
exception_str = '{}: {}'.format(exc.__class__.__name__, exc)
else:
exception_str = exc.__class__.__name__
response.data = {'exception': exception_str}
logger.warning('%s - Exception: %s - Data received %s',
context['request'].build_absolute_uri(),
exception_str,
context['request'].data)
return response
示例6: exception_handler
# 需要导入模块: from rest_framework import views [as 别名]
# 或者: from rest_framework.views import exception_handler [as 别名]
def exception_handler(exc, context):
"""
Django REST handles 4xx exceptions itself, so they don't get logged to the
'django.request' logger by default. This exception handler logs them as if
Django was handling them then calls the default Django REST handler. This
makes the project logging behavior more consistent (both 4xx's and 5xx's
are sent to the 'django.request' logger)
"""
res = default_exception_handler(exc, context)
if res is not None and is_client_error(res.status_code):
request = context['request']
logger.warn(
'%s (params: %s) (data: %s) (response: %s)', request.path,
request.query_params, request.data, res.data,
extra={
'status_code': res.status_code, 'request': request
}
)
return res
示例7: friendly_exception_handler
# 需要导入模块: from rest_framework import views [as 别名]
# 或者: from rest_framework.views import exception_handler [as 别名]
def friendly_exception_handler(exc, context):
response = exception_handler(exc, context)
if not response and settings.CATCH_ALL_EXCEPTIONS:
exc = APIException(exc)
response = exception_handler(exc, context)
if response is not None:
if is_pretty(response):
return response
error_message = response.data['detail']
error_code = settings.FRIENDLY_EXCEPTION_DICT.get(
exc.__class__.__name__)
response.data.pop('detail', {})
response.data['code'] = error_code
response.data['message'] = error_message
response.data['status_code'] = response.status_code
# response.data['exception'] = exc.__class__.__name__
return response
示例8: exception_handler
# 需要导入模块: from rest_framework import views [as 别名]
# 或者: from rest_framework.views import exception_handler [as 别名]
def exception_handler(exc, context):
"""
自定义异常处理
:param exc: 别的地方抛的异常就会传给exc
:param context: 字典形式。抛出异常的上下文(即抛出异常的出处;即抛出异常的视图)
:return: Response响应对象
"""
# 调用drf框架原生的异常处理方法,把异常和异常出处交给他处理,如果是序列化器异常就直接处理,处理之后就直接返回
response = drf_exception_handler(exc, context)
#如果响应为空表示不是序列化器异常,补充数据库异常
if response is None:
view = context['view']
if isinstance(exc, DatabaseError) or isinstance(exc, RedisError):
# 数据库异常
logger.error('[%s] %s' % (view, exc))
response = Response({'message': '服务器内部错误'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)
return response
示例9: drf_exception_handler
# 需要导入模块: from rest_framework import views [as 别名]
# 或者: from rest_framework.views import exception_handler [as 别名]
def drf_exception_handler(exc, context):
response = exception_handler(exc, context)
if not response and settings.CATCH_ALL_EXCEPTIONS:
logging.exception(exc)
exc = APIException(exc)
response = exception_handler(exc, context)
if response is not None:
response.status_code = HTTP_200_OK
if is_pretty(response):
return response
error_message = response.data.pop('detail', '')
error_code = settings.FRIENDLY_EXCEPTION_DICT.get(
exc.__class__.__name__)
response.data['code'] = error_code
response.data['message'] = error_message
return response
示例10: core_exception_handler
# 需要导入模块: from rest_framework import views [as 别名]
# 或者: from rest_framework.views import exception_handler [as 别名]
def core_exception_handler(exc, context):
# If an exception is thrown that we don't explicitly handle here, we want
# to delegate to the default exception handler offered by DRF. If we do
# handle it, we will still want access to the response
# generated by DRF, so we get it up front.
response = exception_handler(exc, context)
handlers = {
'ProfileDoesNotExist': _handle_generic_error,
'ValidationError': _handle_generic_error
}
# This is how we identify the type of the current exception. We will use
# this in a moment to see whether we should handle this exception or let
# Django REST Framework do its thing.
exception_class = exc.__class__.__name__
if exception_class in handlers:
# If this exception is one that we can handle, then handle it. Otherwise,
# return the response generated earlier by the default exception
# handler.
return handlers[exception_class](exc, context, response)
return response
示例11: base_exception_handler
# 需要导入模块: from rest_framework import views [as 别名]
# 或者: from rest_framework.views import exception_handler [as 别名]
def base_exception_handler(exc, context):
# Call DRF's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, context)
# check that a ValidationError exception is raised
if isinstance(exc, ValidationError):
# here prepare the 'custom_error_response' and
# set the custom response data on response object
if response.data.get("username", None):
response.data = response.data["username"][0]
elif response.data.get("email", None):
response.data = response.data["email"][0]
elif response.data.get("password", None):
response.data = response.data["password"][0]
return response
示例12: handle_validation_error
# 需要导入模块: from rest_framework import views [as 别名]
# 或者: from rest_framework.views import exception_handler [as 别名]
def handle_validation_error(exc, context):
"""
Handle the given ValidationError and return a response.
:param exc: The exception that was thrown.
:param context: The context in which the exception was thrown.
:return: A Django Response object.
"""
response = exception_handler(exc, context)
response.status_code = 400
response.data = {
"status_code": 400,
"message": "Invalid input received.",
"detail": "There was an error with the data that you submitted. Please check your input and try again.",
"error_fields": exc.get_full_details(),
}
return response
示例13: handle_non_field_error
# 需要导入模块: from rest_framework import views [as 别名]
# 或者: from rest_framework.views import exception_handler [as 别名]
def handle_non_field_error(exc, context):
"""
Handle the given WsRestNonFieldException and return a response.
:param exc: The exception that was thrown.
:param context: The context in which the exception was thrown.
:return: A Django Response object.
"""
response = exception_handler(exc, context)
response.status_code = 400
response.data = {
"status_code": 400,
"message": "Invalid input received.",
"detail": exc.detail,
"error_fields": [],
}
return response
示例14: custom_exception_handler
# 需要导入模块: from rest_framework import views [as 别名]
# 或者: from rest_framework.views import exception_handler [as 别名]
def custom_exception_handler(exc, context):
"""
Custom exception handler for rest api views
"""
# Call REST framework's default exception handler first,
# to get the standard error response.
log.exception("An exception was intercepted by custom_exception_handler")
response = exception_handler(exc, context)
# if it is handled, just return the response
if response is not None:
return response
# Otherwise format the exception only in specific cases
if isinstance(exc, ImproperlyConfigured):
# send the exception to Sentry anyway
client.capture_exception()
formatted_exception_string = "{0}: {1}".format(type(exc).__name__, str(exc))
return Response(
status=status.HTTP_500_INTERNAL_SERVER_ERROR,
data=[formatted_exception_string]
)
return None
示例15: exception_errors_format_handler
# 需要导入模块: from rest_framework import views [as 别名]
# 或者: from rest_framework.views import exception_handler [as 别名]
def exception_errors_format_handler(exc, context):
response = exception_handler(exc, context)
# If unexpected error occurs (server error, etc.)
if response is None:
return response
formatter = ErrorsFormatter(exc)
response.data = formatter()
return response