exception handling middleware

 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

  1. Sort Table Headers by insin 6 years, 9 months ago
  2. I18n URLs via Middleware by zerok 6 years, 8 months ago
  3. Extensible exception handling middleware by kcarnold 6 years, 1 month ago
  4. Ajax error handling by kcarnold 5 years, 10 months ago
  5. A action decorator for URLs by Batiste 6 years ago

Comments

Spike^ekipS (on April 30, 2008):

If settings.DEBUG is True, it's natural to show the django native error page, I guess.

#

ageldama (on May 7, 2008):

this is not for error page. this middleware is intend to use when you want exception handling as request forwearding :-) (like AOP)

#

(Forgotten your password?)