<code>
is_loaded = False
if not is_loaded:
is_loaded = True
#... ExceptionHandlingMiddleware as EHM
import views
EHM.append(views.AuthFailError, views.auth_fail) # when AuthFailError thrown it redirects to auth_fail
view function.
</code>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | class ExceptionHandlingMiddleware:
"""
해당 예외에 대해서 등록한 뷰함수를 그 예외가 발생하면 실행하도록.
1. settings.MIDDLEWARES에 등록하기
2. ExceptionHandlingMiddleware.append(...)으로 예외클래스에 대해서 뷰함수 등록하기
"""
#
__exception_handlers__ = [
# (exception_type, handling_view_function, args, kwargs)
]
@classmethod
def append(klass, exc_type, handling_viewfunc, args=[], kwargs={}):
"""
주어진 exc_type의 예외에 대해서 handling_viewfunc로 응답을 되돌리도록 등록하기
"""
#
if exc_type in [ t[0] for t in klass.__exception_handlers__ ]:
raise ValueError("exception '%s' is already had handler(%s)" % \
(str(exc_type), str(handling_viewfunc)))
#
t = (exc_type, handling_viewfunc, args, kwargs)
return klass.__exception_handlers__.append(t)
def process_exception(self, request, exception):
for t in ExceptionHandlingMiddleware.__exception_handlers__:
exc_type, handler, args, kwargs = t
if isinstance(exception, exc_type):
kwargs2 = kwargs.copy()
kwargs2['exception_type'] = exc_type
kwargs2['exception'] = exception
return handler(request, *args, **kwargs2)
return None
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
If settings.DEBUG is True, it's natural to show the django native error page, I guess.
#
this is not for error page. this middleware is intend to use when you want exception handling as request forwearding :-) (like AOP)
#
Please login first before commenting.