1👍
you wrap all view in django application and catch db exception
class DbExceptCatcherMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
def catcher(view_func, view_args, view_kwargs):
def f(view_args, view_kwargs):
try:
return view_func(*view_args, **view_kwargs)
except DatabaseError:
raise HttpResponse(content='Unknown MySQL server host', status=502)
return f
view_func = catcher(view_func, view_args, view_kwargs)
in settings.py
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'path.to.module.DbExceptCatcherMiddleware',
)
this may help, but i’m not sure on. i not test this code.
Or you can use decorators
def wrapp_excep(func):
def f(*arg, **kwd):
try:
return func(*arg, **kwd)
except DatabaseError:
raise HttpResponse(content='Unknown MySQL server host', status=502)
return f
@wrapp_excep
def your_view_1(request):
....
@wrapp_excep
def your_view_2(request):
....
👤sheh
Source:stackexchange.com