[Answer]-How to retain stacktrace when you must return a value?

1👍

If you want just to log it, then do so. The logging.exception method will log a message and append a traceback automatically:

except PermissionDenied as err:
    logger.exception('Permission was denied: %s', err)

0👍

StackTrace of Errors on our custom Template in python

except PermissionDenied:
        return render(request, 'friendly_error_page.html', context)

is not a good way in django gor dealing with 403 , 4xx or 5xx errors.

If we want to show exceptions which are generated , on ur template(403.html) then we could write your own 403 view, grabbing the exception and passing it to your 403 template.

Steps:

#.In views.py:

 import sys,traceback

    def custom_403(request):
    t = loader.get_template('403.html')
    logger.info("custom msg",sys.exc_info()) // for traceback
    type, value, tb = sys.exc_info()
    return HttpResponseServerError(t.render(Context({
    'exception_value': value,
    'value':type,
    'tb':traceback.format_exception(type, value,
                                          tb)
},RequestContext(request))))

#.In Main Urls.py:

 from django.conf.urls.defaults import *
    handler403 = 'Project.web.services.views.custom_403'

and if you want to show stacktrace to user use this template otherwise your custom template

#.In Template(403.html):

{{ exception_value }}{{value}}{{tb}}

Leave a comment