Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Catch API exception and serve helpful error response #460

Merged
merged 5 commits into from
May 5, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 20 additions & 4 deletions apps/greencheck/api/legacy_views.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,24 @@
import json
import logging

from apps.accounts.models import Hostingprovider, Datacenter

from django.views.decorators.cache import cache_page
from django_countries import countries
from rest_framework import response
from rest_framework import exceptions
from rest_framework.decorators import api_view, permission_classes, renderer_classes
from rest_framework.permissions import AllowAny
from rest_framework_jsonp.renderers import JSONPRenderer

from ...accounts.models import Hostingprovider
from ..domain_check import GreenDomainChecker
from ..models import Greencheck, GreenDomain
from .legacy_image_view import legacy_greencheck_image
from ..serializers import GreenDomainSerializer

# we import legacy_greencheck_image, to provide one module to import all
# legacy API views from
from .legacy_image_view import legacy_greencheck_image # noqa

logger = logging.getLogger(__name__)

checker = GreenDomainChecker()
Expand Down Expand Up @@ -112,7 +117,6 @@ def directory(request):
country_list = {}

for country in countries:

country_obj = {
"iso": country.code,
"tld": f".{country.code.lower()}",
Expand All @@ -136,7 +140,19 @@ def directory_provider(self, id):
what they do, and evidence supporting their
sustainability claims
"""
provider = Hostingprovider.objects.get(pk=id)
try:
provider_id = int(id)
except ValueError as ex:
logger.warning(ex)
raise exceptions.NotAcceptable(
(
"You need to send a valid numeric ID to identify the "
"provider you are requesting information about. "
f"Received ID was: '{id}'"
)
)

provider = Hostingprovider.objects.get(pk=provider_id)
datacenters = [dc.legacy_representation() for dc in provider.datacenter.all() if dc]

# basic case, no datacenters or certificates
Expand Down
28 changes: 26 additions & 2 deletions apps/greencheck/tests/test_legacy_directory.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@

@pytest.fixture
def green_dc_certificate(datacenter):

return DatacenterCertificate(
energyprovider="Some Energy Co.",
mainenergy_type="mixed",
Expand Down Expand Up @@ -138,7 +137,6 @@ class TestGreenWebDirectoryDetail:
"""

def test_directory_provider(self, db, hosting_provider_a, client):

hosting_provider_a.save()
url_path = reverse("legacy-directory-detail", args=[hosting_provider_a.id])

Expand Down Expand Up @@ -255,3 +253,29 @@ def test_directory_provider_with_certificates(
]:
assert key in cert

def test_directory_provider_raises_against_undefined_provider(
self, db, hosting_provider_a, client
):
"""
Make sure that when client side code tries to request a provider
with the id of 'undefined' we serve an appropriate error
40x response, rather than raising an helpful 500 server error
"""
# Given: a valid hosting provider, but an invalid id of 'undefined' from
# client side code making requests
hosting_provider_a.save()
url_path = reverse("legacy-directory-detail", args=["undefined"])

# When: I send an API reqeest
resp = client.get(url_path)

# Then: I should receive a helpful API error response
assert resp.status_code == 406

# And: with hints about how to fix my request
error_detail = resp.data["detail"]
error_message = str(error_detail)

assert error_detail.code == "not_acceptable"
assert "You need to send a valid numeric ID" in error_message
assert "Received ID was: 'undefined'" in error_message