Skip to content

Commit

Permalink
Nice 404 error message
Browse files Browse the repository at this point in the history
  • Loading branch information
boxed committed Feb 19, 2022
1 parent 89b647d commit e5f300b
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 1 deletion.
13 changes: 13 additions & 0 deletions src/whitenoise/middleware.py
Expand Up @@ -11,6 +11,7 @@
from django.urls import get_script_prefix

from .base import WhiteNoise
from .responders import MissingFileError
from .string_utils import decode_if_byte_string, ensure_leading_trailing_slash

__all__ = ["WhiteNoiseMiddleware"]
Expand Down Expand Up @@ -68,6 +69,18 @@ def process_request(self, request):
if static_file is not None:
return self.serve(static_file, request)

if settings.DEBUG and request.path.startswith(settings.STATIC_URL):
from django.contrib.staticfiles.finders import get_finders
finders = get_finders()
app_dirs = []
for finder in finders:
for storage in finder.storages.values():
app_dirs.append(storage.location)
app_dirs = "\n ".join(sorted(app_dirs))
raise MissingFileError(f"""{request.path} not found. Searched these paths:
{app_dirs}""")

@staticmethod
def serve(static_file, request):
response = static_file.get_response(request.method, request.META)
Expand Down
11 changes: 10 additions & 1 deletion tests/django_urls.py
@@ -1,3 +1,12 @@
from __future__ import annotations

urlpatterns = []
from django.urls import path


def avoid_django_default_welcome_page():
pass


urlpatterns = [
path('', avoid_django_default_welcome_page)
]
20 changes: 20 additions & 0 deletions tests/test_django_whitenoise.py
Expand Up @@ -3,6 +3,7 @@
import shutil
import tempfile
from contextlib import closing
from pathlib import Path
from urllib.parse import urljoin, urlparse

import django
Expand All @@ -15,6 +16,7 @@
from django.utils.functional import empty

from whitenoise.middleware import WhiteNoiseFileResponse, WhiteNoiseMiddleware
from whitenoise.responders import MissingFileError

from .utils import AppServer, Files

Expand Down Expand Up @@ -210,3 +212,21 @@ def test_relative_static_url(server, static_files, _collect_static):
url = storage.staticfiles_storage.url(static_files.js_path)
response = server.get(url)
assert response.content == static_files.js_content


def test_404_in_prod(server):
response = server.get(settings.STATIC_URL + 'garbage')
assert response.status_code == 404


@override_settings(DEBUG=True)
def test_error_message(server):
response = server.get(settings.STATIC_URL + 'garbage')
print(response.content.decode())
app_dirs = Path(__file__).parent / 'test_files' / 'static'

expected = f"""{settings.STATIC_URL + 'garbage'} not found. Searched these paths:
{app_dirs}"""

assert expected in str(response.content.decode())

0 comments on commit e5f300b

Please sign in to comment.