Python rest_framework.status.HTTP_500_INTERNAL_SERVER_ERROR Examples
The following are 30
code examples of rest_framework.status.HTTP_500_INTERNAL_SERVER_ERROR().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
rest_framework.status
, or try the search function
.
Example #1
Source File: utils.py From micromasters with BSD 3-Clause "New" or "Revised" License | 7 votes |
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
Example #2
Source File: views.py From resilient-python-examples with MIT License | 6 votes |
def get(self, request, request_id): """ Fetch results corresponding to given request id """ request_id = request_id.rstrip('/') context = SearchContext.load(request_id) if context is None: # We return "no content" because we have none # 404 will cause the custom threat service caller to stop processing return Response({"error": "'{}' was not found".format(request_id)}, status.HTTP_204_NO_CONTENT) try: matching_threats = search_artifacts(context.type, context.value) response = process_threat_results(matching_threats, context) # Keep broad exception handler, as this is an entry point to the service interface except Exception as ex: # pylint: disable=broad-except response = Response({'error': '{}'.format(str(ex))}, status.HTTP_500_INTERNAL_SERVER_ERROR) return response
Example #3
Source File: uploaders.py From django-drf-filepond with BSD 3-Clause "New" or "Revised" License | 6 votes |
def handle_upload(self, request, upload_id, file_id=None): # Since the upload_id is being provided here as a paramter, we check # it is valid. This should be done by the DB but for some DBs, e.g. # SQLite field length validation isn't handled. The same check is # done for file_id in the case of POST requests. if not self._upload_id_valid(upload_id): return Response('Invalid ID for handling upload.', status=status.HTTP_500_INTERNAL_SERVER_ERROR) if request.method == 'PATCH': return self._handle_chunk_upload(request, upload_id) elif request.method == 'HEAD': return self._handle_chunk_restart(request, upload_id) elif request.method == 'POST': if not self._file_id_valid(file_id): return Response('Invalid ID for handling upload.', status=status.HTTP_500_INTERNAL_SERVER_ERROR) return self._handle_new_chunk_upload(request, upload_id, file_id)
Example #4
Source File: views.py From Project-Dashboard-with-Django with MIT License | 6 votes |
def post(self, request): data = request.data['checkout'] total = len(data) * 5 queryset = CharityModel.objects.all() my_profile = get_object_or_404(MyProfile, owner=request.user) if my_profile.my_wallet < total: return Response({"error": "Insufficient leancoins to proceed with the transaction."}, status=status.HTTP_400_BAD_REQUEST) try: for element in data: charity = get_object_or_404(queryset, pk=int(element)) DonationModel.objects.create(donor=request.user, charity=charity) my_profile.my_wallet -= total my_profile.save() except Http404: return Response({"error": "We couldn't proceed with transaction at this time. Try again later"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) return Response({"message": "You have successfully paid"}, status=status.HTTP_201_CREATED)
Example #5
Source File: publication.py From ecommerce with GNU Affero General Public License v3.0 | 6 votes |
def _save_and_publish(self, data, course_id=None): """Create or update a Course and associated products, then publish the result.""" if course_id is not None: data['id'] = course_id serializer = self.get_serializer(data=data) is_valid = serializer.is_valid(raise_exception=True) if not is_valid: return None created, failure, message = serializer.save() if failure: return Response({'error': message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) content = serializer.data content['message'] = message if message else None return Response(content, status=status.HTTP_201_CREATED if created else status.HTTP_200_OK)
Example #6
Source File: views.py From django-telegram-bot with BSD 3-Clause "New" or "Revised" License | 6 votes |
def post(self, request, token): serializer = UpdateSerializer(data=request.data) if serializer.is_valid(): serializer.save() try: bot = Bot.objects.get(token=token) bot.handle(Update.de_json(request.data, bot._bot)) except Bot.DoesNotExist: logger.warning("Token %s not associated to a bot" % token) return Response(serializer.errors, status=status.HTTP_404_NOT_FOUND) except: exc_info = sys.exc_info() traceback.print_exception(*exc_info) logger.error("Error processing %s for token %s" % (request.data, token)) return Response(serializer.errors, status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: return Response(serializer.data, status=status.HTTP_200_OK) logger.error("Validation error: %s from message %s" % (serializer.errors, request.data)) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #7
Source File: refunds.py From ecommerce with GNU Affero General Public License v3.0 | 6 votes |
def update(self, request, *args, **kwargs): APPROVE = 'approve' DENY = 'deny' APPROVE_PAYMENT_ONLY = 'approve_payment_only' action = request.data.get('action', '').lower() if action not in (APPROVE, DENY, APPROVE_PAYMENT_ONLY): raise ParseError('The action [{}] is not valid.'.format(action)) with transaction.atomic(): refund = self.get_object() result = False if action in (APPROVE, APPROVE_PAYMENT_ONLY): revoke_fulfillment = action == APPROVE result = refund.approve(revoke_fulfillment=revoke_fulfillment) elif action == DENY: result = refund.deny() http_status = status.HTTP_200_OK if result else status.HTTP_500_INTERNAL_SERVER_ERROR serializer = self.get_serializer(refund) return Response(serializer.data, status=http_status)
Example #8
Source File: enterprise.py From ecommerce with GNU Affero General Public License v3.0 | 6 votes |
def retrieve(self, request, **kwargs): endpoint_request_url = urlparse(request.build_absolute_uri())._replace(query=None).geturl() try: catalog = get_enterprise_catalog( site=request.site, enterprise_catalog=kwargs.get('enterprise_catalog_uuid'), limit=request.GET.get('limit', DEFAULT_CATALOG_PAGE_SIZE), page=request.GET.get('page', '1'), endpoint_request_url=endpoint_request_url ) except (ReqConnectionError, SlumberHttpBaseException, Timeout) as exc: logger.exception( 'Unable to retrieve catalog for enterprise customer! customer: %s, Exception: %s', kwargs.get('enterprise_catalog_uuid'), exc ) return Response( {'error': 'Unable to retrieve enterprise catalog. Exception: {}'.format(six.text_type(exc))}, status=status.HTTP_500_INTERNAL_SERVER_ERROR ) return Response(catalog)
Example #9
Source File: orders.py From ecommerce with GNU Affero General Public License v3.0 | 6 votes |
def fulfill(self, request, number=None): # pylint: disable=unused-argument """ Fulfill order """ order = self.get_object() if not order.is_fulfillable: return Response(status=status.HTTP_406_NOT_ACCEPTABLE) # Get email_opt_in from the query parameters if it exists, defaulting to false email_opt_in = request.query_params.get('email_opt_in', False) == 'True' logger.info('Attempting fulfillment of order [%s]...', order.number) with transaction.atomic(): post_checkout.send( sender=post_checkout, order=order, request=request, email_opt_in=email_opt_in, ) if order.is_fulfillable: logger.warning('Fulfillment of order [%s] failed!', order.number) return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR) serializer = self.get_serializer(order) return Response(serializer.data)
Example #10
Source File: courses.py From ecommerce with GNU Affero General Public License v3.0 | 6 votes |
def publish(self, request, pk=None): # pylint: disable=unused-argument """ Publish the course to LMS. """ course = self.get_object() published = False msg = 'Course [{course_id}] was not published to LMS ' \ 'because the switch [publish_course_modes_to_lms] is disabled.' if waffle.switch_is_active('publish_course_modes_to_lms'): published = course.publish_to_lms() if published: msg = 'Course [{course_id}] was successfully published to LMS.' else: msg = 'An error occurred while publishing [{course_id}] to LMS.' return Response({'status': msg.format(course_id=course.id)}, status=status.HTTP_200_OK if published else status.HTTP_500_INTERNAL_SERVER_ERROR)
Example #11
Source File: views_test.py From micromasters with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_view_response_improperly_configured(self): """ Test that the SearchResultMailView will raise ImproperlyConfigured if mailgun returns 401, which results in returning 500 since micromasters.utils.custom_exception_handler catches ImproperlyConfigured """ with patch( 'mail.views.get_all_query_matching_emails', autospec=True, return_value=self.email_results ), patch( 'mail.views.MailgunClient' ) as mock_mailgun_client, patch( 'mail.views.get_mail_vars', autospec=True, return_value=self.email_vars, ) as mock_get_mail_vars: mock_mailgun_client.send_batch.side_effect = ImproperlyConfigured resp = self.client.post(self.search_result_mail_url, data=self.request_data, format='json') assert resp.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR mock_get_mail_vars.assert_called_once_with(self.email_results)
Example #12
Source File: api.py From KubeOperator with Apache License 2.0 | 6 votes |
def post(self, request, *args, **kwargs): weixin_config = request.data weixin = WorkWeiXin(corp_id=weixin_config['WEIXIN_CORP_ID'], corp_secret=weixin_config['WEIXIN_CORP_SECRET'], agent_id=weixin_config['WEIXIN_AGENT_ID']) result = weixin.get_token() if result.success: redis_cli = redis.StrictRedis(host=kubeoperator.settings.REDIS_HOST, port=kubeoperator.settings.REDIS_PORT) redis_cli.set('WORK_WEIXIN_TOKEN', result.data['access_token'], result.data['expires_in']) if weixin_config.get('WEIXIN_TEST_USER') is not None and weixin_config['WEIXIN_TEST_USER'] != '': res = weixin.send_markdown_msg(receivers=weixin_config['WEIXIN_TEST_USER'], content={'content': '测试消息'}, token=result.data['access_token']) if res.success: return Response(data={'msg': '校验成功!'}, status=status.HTTP_200_OK) else: return Response(data={'msg': '校验失败!' + json.dumps(res.data)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: return Response(data={'msg': '校验成功!'}, status=status.HTTP_200_OK) else: return Response(data={'msg': '校验失败!' + json.dumps(result.data)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
Example #13
Source File: api_test.py From micromasters with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_add_channel_failed_create_channel(mock_staff_client, mocker): """If client.channels.create fails an exception should be raised""" response_500 = Response() response_500.status_code = statuses.HTTP_500_INTERNAL_SERVER_ERROR mock_staff_client.channels.create.return_value.raise_for_status.side_effect = HTTPError(response=response_500) with pytest.raises(ChannelCreationException) as ex: api.add_channel( Search.from_dict({}), "title", "name", "description", "channel_type", 123, 456, ) assert ex.value.args[0] == "Error creating channel name" mock_staff_client.channels.create.return_value.raise_for_status.assert_called_with() assert mock_staff_client.channels.create.call_count == 1 assert PercolateQuery.objects.count() == 0 assert Channel.objects.count() == 0
Example #14
Source File: views_test.py From micromasters with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_500_error_context_logged_out(self): """ Assert context values for 500 error page when logged out """ # case with specific page with patch('ui.templatetags.render_bundle._get_bundle') as get_bundle: response = self.client.get('/500/') assert response.context['authenticated'] is False assert response.context['name'] == "" assert response.context['is_public'] is True assert response.context['has_zendesk_widget'] is True self.assertContains(response, 'Share this page', status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) bundles = [bundle[0][1] for bundle in get_bundle.call_args_list] assert set(bundles) == { 'public', 'sentry_client', 'style', 'style_public', 'zendesk_widget', }
Example #15
Source File: tests_view.py From koku with GNU Affero General Public License v3.0 | 6 votes |
def test_list_cost_model_rate_rbac_access(self): """Test GET /cost-models with an rbac user.""" user_data = self._create_user_data() customer = self._create_customer_data() request_context = self._create_request_context(customer, user_data, create_customer=True, is_admin=False) self.initialize_request(context={"request_context": request_context, "user_data": user_data}) test_matrix = [ {"access": {"rate": {"read": [], "write": []}}, "expected_response": status.HTTP_403_FORBIDDEN}, {"access": {"rate": {"read": ["*"], "write": []}}, "expected_response": status.HTTP_200_OK}, { "access": {"rate": {"read": ["not-a-uuid"], "write": []}}, "expected_response": status.HTTP_500_INTERNAL_SERVER_ERROR, }, ] client = APIClient() for test_case in test_matrix: with patch.object(RbacService, "get_access_for_user", return_value=test_case.get("access")): url = reverse("cost-models-list") caches["rbac"].clear() response = client.get(url, **request_context["request"].META) self.assertEqual(response.status_code, test_case.get("expected_response"))
Example #16
Source File: views.py From safe-relay-service with MIT License | 6 votes |
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
Example #17
Source File: utils_test.py From micromasters with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_generate_mailgun_response_json_with_failed_json_call(self): """ Tests that generate_mailgun_response_json() returns without erroring if Response.json() call fails for non 401 status code """ # Response.json() error response = Mock( spec=Response, status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, json=lambda: (_ for _ in []).throw(ValueError), # To get .json() to throw ValueError reason="reason" ) self.assertDictEqual( generate_mailgun_response_json(response), {"message": response.reason} )
Example #18
Source File: utils_test.py From micromasters with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_improperly_configured(self, exception_to_raise, mock_sentry): """ Test a standard exception not handled by default by the rest framework """ exp = exception_to_raise('improperly configured') resp = custom_exception_handler(exp, self.context) assert resp.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR assert resp.data == ['{0}: improperly configured'.format(exception_to_raise.__name__)] mock_sentry.assert_called_once_with()
Example #19
Source File: views.py From foundation.mozilla.org with Mozilla Public License 2.0 | 5 votes |
def send_to_sqs(sqs, queue_url, message, type='petition'): if settings.DEBUG is True: logger.info(f'Sending {type} message: {message}') if not sqs: # TODO: can this still kick in now that we have an SQS proxy object? logger.info('Faking a success message (debug=true, sqs=nonexistent).') return Response({'message': 'success (faked)'}, 201) if queue_url is None: logger.warning(f'{type} was not submitted: No {type} SQS url was specified') return Response({ 'message': 'success', 'details': 'nq' }, 201) try: response = sqs.send_message( QueueUrl=queue_url, MessageBody=message ) except Exception as error: logger.error(f'Failed to send {type} with: {error}') return Response( {'error': f'Failed to queue up {type}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR ) if 'MessageId' in response and response['MessageId']: return Response({ 'message': 'success', 'details': response['MessageId'] }, 201) else: return Response( {'error': f'Something went wrong with {type}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR )
Example #20
Source File: middleware.py From ChRIS_ultron_backEnd with MIT License | 5 votes |
def api_500(request): return RenderedResponse({'detail': 'Internal server error', 'request':request, 'status': status.HTTP_500_INTERNAL_SERVER_ERROR})
Example #21
Source File: views_test.py From micromasters with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_enrollment_fails(self, mock_refresh, mock_edx_enr): # pylint: disable=unused-argument """ Test error when backend raises an exception """ error = HTTPError() error.response = MagicMock() error.response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR mock_edx_enr.side_effect = error resp = self.client.post(self.url, {'course_id': self.course_id}, format='json') assert resp.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR # the response has a structure like {"error": "<message>"} assert isinstance(resp.data, dict) assert 'error' in resp.data assert mock_edx_enr.call_count == 1 # assert just the second argument, since the first is `self` assert mock_edx_enr.call_args[0][1] == self.course_id # if instead edX returns a 400 error, an exception is raised by # the view and the user gets a different error message error.response.status_code = status.HTTP_400_BAD_REQUEST mock_edx_enr.side_effect = error resp = self.client.post(self.url, {'course_id': self.course_id}, format='json') assert resp.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR assert isinstance(resp.data, list) assert len(resp.data) == 1 assert PossiblyImproperlyConfigured.__name__ in resp.data[0] # if the error from the call to edX is is not HTTPError, the user gets a normal json error mock_edx_enr.side_effect = ValueError() resp = self.client.post(self.url, {'course_id': self.course_id}, format='json') assert resp.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR # the response has a structure like {"error": "<message>"} assert isinstance(resp.data, dict) assert 'error' in resp.data
Example #22
Source File: exception.py From apixu-python with MIT License | 5 votes |
def handler(exc, context): message = 'Internal Server Error' code = status.HTTP_500_INTERNAL_SERVER_ERROR if isinstance(exc, ApixuException): if exc.code == errors.NO_LOCATION_FOUND_FOR_QUERY: message = 'Could not find location.' code = status.HTTP_404_NOT_FOUND logging.exception(exc) if isinstance(exc, ValueError): message = str(exc) code = status.HTTP_400_BAD_REQUEST return Response({'error': message}, status=code)
Example #23
Source File: rest_api.py From scirius with GNU General Public License v3.0 | 5 votes |
def get(self, request, format=None): try: return self._get(request, format) except ESError as e: return Response({'error: ES request failed, %s' % unicode(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
Example #24
Source File: hook_log.py From kpi with GNU Affero General Public License v3.0 | 5 votes |
def retry(self, request, uid=None, *args, **kwargs): """ Retries to send data to external service. :param request: rest_framework.request.Request :param uid: str :return: Response """ response = {"detail": "", "status_code": KOBO_INTERNAL_ERROR_STATUS_CODE} status_code = status.HTTP_200_OK hook_log = self.get_object() if hook_log.can_retry(): hook_log.change_status() success = hook_log.retry() if success: # Return status_code of remote server too. # `response["status_code"]` is not the same as `status_code` response["detail"] = hook_log.message response["status_code"] = hook_log.status_code else: response["detail"] = _("An error has occurred when sending the data. Please try again later.") status_code = status.HTTP_500_INTERNAL_SERVER_ERROR else: response["detail"] = _("Data is being or has already been processed") status_code = status.HTTP_400_BAD_REQUEST return Response(response, status=status_code)
Example #25
Source File: messenger_hook.py From permabots with BSD 3-Clause "New" or "Revised" License | 5 votes |
def post(self, request, hook_id): """ Process Messenger webhook. 1. Get an enabled Messenger bot 3. For each message serialize 4. For each message create :class:`MessengerMessage <permabots.models.messenger_api.MessengerMessage>` 5. Delay processing of each message to a task 6. Response provider """ try: bot = caching.get_or_set(MessengerBot, hook_id) except MessengerBot.DoesNotExist: logger.warning("Hook id %s not associated to a bot" % hook_id) return Response(status=status.HTTP_404_NOT_FOUND) logger.debug("Messenger Bot %s attending request %s" % (bot, request.data)) webhook = Webhook.from_json(request.data) for webhook_entry in webhook.entries: for webhook_message in webhook_entry.messaging: try: if webhook_message.is_delivery: raise OnlyTextMessages message = self.create_message(webhook_message, bot) if bot.enabled: logger.debug("Messenger Bot %s attending request %s" % (bot, message)) handle_messenger_message.delay(message.id, bot.id) else: logger.error("Message %s ignored by disabled bot %s" % (message, bot)) except OnlyTextMessages: logger.warning("Not text message %s for bot %s" % (message, hook_id)) except: exc_info = sys.exc_info() traceback.print_exception(*exc_info) logger.error("Error processing %s for bot %s" % (webhook_message, hook_id)) return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR) return Response(status=status.HTTP_200_OK)
Example #26
Source File: telegram_hook.py From permabots with BSD 3-Clause "New" or "Revised" License | 5 votes |
def post(self, request, hook_id): """ Process Telegram webhook. 1. Serialize Telegram message 2. Get an enabled Telegram bot 3. Create :class:`Update <permabots.models.telegram_api.Update>` 5. Delay processing to a task 6. Response provider """ serializer = UpdateSerializer(data=request.data) if serializer.is_valid(): try: bot = caching.get_or_set(TelegramBot, hook_id) except TelegramBot.DoesNotExist: logger.warning("Hook id %s not associated to an bot" % hook_id) return Response(serializer.errors, status=status.HTTP_404_NOT_FOUND) try: update = self.create_update(serializer, bot) if bot.enabled: logger.debug("Telegram Bot %s attending request %s" % (bot.token, request.data)) handle_update.delay(update.id, bot.id) else: logger.error("Update %s ignored by disabled bot %s" % (update, bot.token)) except OnlyTextMessages: logger.warning("Not text message %s for bot %s" % (request.data, hook_id)) return Response(status=status.HTTP_200_OK) except: exc_info = sys.exc_info() traceback.print_exception(*exc_info) logger.error("Error processing %s for bot %s" % (request.data, hook_id)) return Response(serializer.errors, status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: return Response(serializer.data, status=status.HTTP_200_OK) logger.error("Validation error: %s from message %s" % (serializer.errors, request.data)) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #27
Source File: permabots_hook.py From permabots with BSD 3-Clause "New" or "Revised" License | 5 votes |
def post(self, request, key): """ Process notitication hooks: 1. Obtain Hook 2. Check Auth 3. Delay processing to a task 4. Respond requester """ try: hook = Hook.objects.get(key=key, enabled=True) except Hook.DoesNotExist: msg = _("Key %s not associated to an enabled hook or bot") % key logger.warning(msg) return Response(msg, status=status.HTTP_404_NOT_FOUND) if hook.bot.owner != request.user: raise exceptions.AuthenticationFailed() try: parsed_data = request.data logger.debug("Hook %s attending request %s" % (hook, parsed_data)) handle_hook.delay(hook.id, parsed_data) except ParseError as e: return Response(str(e), status=status.HTTP_400_BAD_REQUEST) except: exc_info = sys.exc_info() traceback.print_exception(*exc_info) msg = _("Error processing %s for key %s") % (request.data, key) logger.error(msg) return Response(msg, status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: return Response(status=status.HTTP_200_OK)
Example #28
Source File: exceptions.py From django-oauth2-server with Mozilla Public License 2.0 | 5 votes |
def custom_exception_handler(exc, context): """ Formats REST exceptions like: { "error": "error_code", "error_description": "description of the error", } :param exc: Exception :return: Response """ # Call REST framework's default exception handler first, # to get the standard error response. response = exception_handler(exc, context) if not response: # Unhandled exceptions (500 internal server errors) response = Response(data={ 'error': 'server_error', 'error_description': unicode(exc), }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) return response if hasattr(exc, 'default_error'): response.data['error'] = exc.default_error else: response.data['error'] = 'api_error' if hasattr(exc, 'default_detail'): response.data['error_description'] = exc.default_detail elif 'detail' in response.data: response.data['error_description'] = response.data['details'] if 'detail' in response.data: del response.data['detail'] return response
Example #29
Source File: handlers.py From django-rest-logger with MIT License | 5 votes |
def rest_exception_handler(exc, context): """ Return the response that should be used for any given exception. By default we handle the REST framework `APIException`, and also Django's built-in `ValidationError`, `Http404` and `PermissionDenied` exceptions. Any unhandled exceptions may return `None`, which will cause a 500 error to be raised. """ if isinstance(exc, exceptions.APIException): headers = {} if getattr(exc, 'auth_header', None): headers['WWW-Authenticate'] = exc.auth_header if getattr(exc, 'wait', None): headers['Retry-After'] = '%d' % exc.wait if isinstance(exc.detail, dict): data = exc.detail elif isinstance(exc.detail, list): data = {'non_field_errors': exc.detail} else: data = {'non_field_errors': [exc.detail]} return Response(data, status=exc.status_code, headers=headers) elif isinstance(exc, Http404): msg = _('Not found.') data = {'non_field_errors': [six.text_type(msg)]} return Response(data, status=status.HTTP_404_NOT_FOUND) elif isinstance(exc, PermissionDenied): msg = _('Permission denied.') data = {'non_field_errors': [six.text_type(msg)]} return Response(data, status=status.HTTP_403_FORBIDDEN) else: log_exception() msg = _('Server Error. Please try again later.') data = {'non_field_errors': [six.text_type(msg)]} return Response(data, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
Example #30
Source File: views.py From koku with GNU Affero General Public License v3.0 | 5 votes |
def __init__(self, message): """Initialize with status code 500.""" self.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR self.detail = {"detail": force_text(message)}