ownage blog

art, anime, technology, manufacturing, and of course GAMES ^^

Nov 3rd, 2008 @ 2:59 pm

Custom Django Exceptions + Flash AJAX workarounds

Recently had an issue with handling exceptions in a pretty et informative manner.

In addition, some of the Flash widgets on the website weren’t able to parse error messages returned by the server because Flash has a limitation that it will only parse server data on a HTTP 200 response (won’t parse squat for 302, 404, 500, etc). While I was at it, I wanted to make some sexy for my AJAX exception handling too.

So added a Django Middleware to take care of everything. Returns a 200 response for flash, a proper 500 for AJAX with a json response, and a custom rendered 500 for all other requests that are not debug.

class PrettyExceptionMiddleware(object):
	"""
	Exception takes care of pretty 500 server error exceptions as well as formatting exceptions
	properly (with proper error codes) for AJAX and Flash.
	"""
	def process_exception(self, request, exception):
		import sys, traceback
		(exc_type, exc_info, tb) = sys.exc_info()
		
		data = {'type':str(exc_type.__name__), 'message':str(exc_info)}
		
		if request.is_flash():
			return HttpResponse(simplejson.dumps(data)) # flash needs 200 response to retrieve server data

		if request.is_ajax():
			return HttpResponseServerError(simplejson.dumps(data))
		
		# treat as normal request
		if not settings.DEBUG:
			log.debug("error type: %s", exc_type.__name__)
			log.debug("error value: %s", exc_info)
			r = render_to_string('500.html', data, request)
			return HttpResponseServerError(r)
				
		return None

The request.is_flash() is a custom method I added in another middleware that boils down to this:

"flash" in request.META.get("HTTP_USER_AGENT", "").lower() 

Cause the user agent for flash requests is generally “Adobe Flash Player 9 yadda yadda.”

HTH

Archive · RSS · Theme by Novembird