https://github.com/swing-collection/swing-error
Django Swing | Error
https://github.com/swing-collection/swing-error
400 403 404 500 django error error-handling errors swing swing-collection
Last synced: about 2 months ago
JSON representation
Django Swing | Error
- Host: GitHub
- URL: https://github.com/swing-collection/swing-error
- Owner: swing-collection
- License: bsd-3-clause
- Created: 2024-06-29T07:50:59.000Z (11 months ago)
- Default Branch: dev
- Last Pushed: 2025-04-06T06:56:43.000Z (about 2 months ago)
- Last Synced: 2025-04-06T07:31:58.710Z (about 2 months ago)
- Topics: 400, 403, 404, 500, django, error, error-handling, errors, swing, swing-collection
- Language: Python
- Homepage: https://www.swing.dj
- Size: 2.13 MB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Contributing: .github/CONTRIBUTING.md
- Funding: .github/FUNDING.yml
- License: LICENSE
- Code of conduct: .github/CODE_OF_CONDUCT.md
- Citation: CITATION.cff
- Codeowners: .github/CODEOWNERS
- Security: .github/SECURITY.md
- Authors: AUTHORS
Awesome Lists containing this project
README
![]()
Swing Error
Django Swing Collection
## Overview
**Swing Error** provides custom error handlers for various HTTP status codes in a Django application. Each error handler is designed to return a custom response with additional functionality and logging capabilities. The custom error handlers cover the following HTTP status codes:
- 400 Bad Request
- 401 Unauthorized
- 403 Forbidden
- 404 Not Found
- 405 Method Not Allowed
- 408 Request Timeout
- 410 Gone
- 429 Too Many Requests
- 500 Internal Server Error## Installation
1. Clone the repository to your local machine.
2. Add the custom error handlers to your Django project.## Setup
### Step 1: Define Custom Response Classes
Create a file named `responses.py` in your Django application directory and define custom response classes for each HTTP status code.
Example for HTTP 400:
```python
# responses.py
from django.http import HttpResponse
from typing import Any, Union
import loggingclass Http400Response(HttpResponse):
status_code = 400def __init__(self, content: Union[bytes, str] = b'', *args: Any, **kwargs: Any) -> None:
super().__init__(content, *args, **kwargs)
self.log_error()def log_error(self) -> None:
logger = logging.getLogger(__name__)
logger.error(f"400 Bad Request: Response initialized with content: {self.content}")
```Repeat this for other status codes (401, 403, 404, 405, 408, 410, 429, 500) as shown in the initial setup.
### Step 2: Update URL Configuration
Update your `urls.py` file to include the custom error handlers.
```python
# urls.py
from django.urls import path
from django.conf.urls import handler400, handler401, handler403, handler404, handler405, handler408, handler410, handler429, handler500
from .responses import (
Http400Response, Http401Response, Http403Response, Http404Response,
Http405Response, Http408Response, Http410Response, Http429Response, Http500Response
)
from .views import home_view, another_viewurlpatterns = [
path('', home_view, name='home'),
path('another/', another_view, name='another'),
]handler400 = lambda request, exception=None: Http400Response("Bad Request: Invalid request.")
handler401 = lambda request, exception=None: Http401Response("Unauthorized: Authentication is required.")
handler403 = lambda request, exception=None: Http403Response("Forbidden: You do not have permission to access this page.")
handler404 = lambda request, exception=None: Http404Response("Not Found: The requested resource was not found.")
handler405 = lambda request, exception=None: Http405Response("Method Not Allowed: This endpoint only supports certain methods.")
handler408 = lambda request, exception=None: Http408Response("Request Timeout: The server timed out waiting for the request.")
handler410 = lambda request, exception=None: Http410Response("Gone: The requested resource is no longer available.")
handler429 = lambda request, exception=None: Http429Response("Too Many Requests: You have exceeded your request limit.")
handler500 = lambda request: Http500Response("Internal Server Error: An unexpected error occurred.")
```### Step 3: Create Custom Templates
Create custom templates for each error handler in your templates directory.
Example for 400 error (templates/errors/400.html):
```html
{{ title }}
{{ header }}
{{ message }}
{{ redirect }}```
Repeat this for other status codes (401, 403, 404, 405, 408, 410, 429, 500) with appropriate content.
### Step 4: Test Custom Error Handlers
Ensure that the custom error handlers are invoked correctly by triggering the respective errors in your application. For example, you can test a 404 error by accessing a non-existent URL.
## Usage
In your views, you can use the custom response classes to return specific error responses as needed. For example:
```python
from django.shortcuts import render
from .responses import Http400Response, Http404Responsedef some_view(request):
if some_condition:
return Http400Response("Bad Request: Invalid data.")
if another_condition:
return Http404Response("Not Found: The requested resource was not found.")
return render(request, 'some_template.html')
```---
## Colophon
Made with ❤️ by **[Scape Agency](https://www.scape.agency)**
### Contributing
Contributions are welcome! Please fork the repository and submit a pull request with your changes.
### License
This project is licensed under the BSD-3-Clause license. See the [LICENSE](LICENSE) file for details.
---
Error Handler App for Django
## Links
### Docs
- https://docs.djangoproject.com/en/3.0/howto/error-reporting/
- https://docs.djangoproject.com/en/3.0/ref/urls/#django.conf.urls.handler400### Templates
- https://codepen.io/akashrajendra/pen/JKKRvQ
- https://webartdevelopers.com/blog/category/500-error-page-html-templates/- https://github.com/wooyek/django-error-views
error_handler/
├── __init__.py
├── admin.py
├── apps.py
├── handlers.py # Error handling logic
├── middleware.py # Middleware for global error capture
├── models.py
├── templates/ # Custom error pages (if HTML responses)
│ └── error.html
├── tests.py
├── urls.py # Routes for testing error responses
└── views.py # Optional views for error simulation