Skip to content

Commit

Permalink
Fixed #18003 -- Preserved tracebacks when re-raising errors.
Browse files Browse the repository at this point in the history
Thanks jrothenbuhler for draft patch, Konark Modi for updates.
  • Loading branch information
konarkmodi authored and carljm committed Mar 19, 2013
1 parent 1fe90b2 commit bc4111b
Show file tree
Hide file tree
Showing 15 changed files with 60 additions and 32 deletions.
3 changes: 2 additions & 1 deletion django/contrib/admin/views/main.py
@@ -1,4 +1,5 @@
import operator
import sys
import warnings
from functools import reduce

Expand Down Expand Up @@ -173,7 +174,7 @@ def get_filters(self, request):
lookup_needs_distinct(self.lookup_opts, key))
return filter_specs, bool(filter_specs), lookup_params, use_distinct
except FieldDoesNotExist as e:
raise IncorrectLookupParameters(e)
six.reraise(IncorrectLookupParameters, IncorrectLookupParameters(e), sys.exc_info()[2])

def get_query_string(self, new_params=None, remove=None):
if new_params is None: new_params = {}
Expand Down
9 changes: 7 additions & 2 deletions django/contrib/gis/db/backends/oracle/introspection.py
@@ -1,5 +1,7 @@
import cx_Oracle
import sys
from django.db.backends.oracle.introspection import DatabaseIntrospection
from django.utils import six

class OracleIntrospection(DatabaseIntrospection):
# Associating any OBJECTVAR instances with GeometryField. Of course,
Expand All @@ -17,8 +19,11 @@ def get_geometry_type(self, table_name, geo_col):
(table_name.upper(), geo_col.upper()))
row = cursor.fetchone()
except Exception as msg:
raise Exception('Could not find entry in USER_SDO_GEOM_METADATA corresponding to "%s"."%s"\n'
'Error message: %s.' % (table_name, geo_col, msg))
new_msg = (
'Could not find entry in USER_SDO_GEOM_METADATA '
'corresponding to "%s"."%s"\n'
'Error message: %s.') % (table_name, geo_col, msg)
six.reraise(Exception, Exception(new_msg), sys.exc_info()[2])

# TODO: Research way to find a more specific geometry field type for
# the column's contents.
Expand Down
8 changes: 6 additions & 2 deletions django/contrib/gis/db/backends/spatialite/base.py
@@ -1,3 +1,4 @@
import sys
from ctypes.util import find_library
from django.conf import settings

Expand All @@ -8,6 +9,7 @@
from django.contrib.gis.db.backends.spatialite.creation import SpatiaLiteCreation
from django.contrib.gis.db.backends.spatialite.introspection import SpatiaLiteIntrospection
from django.contrib.gis.db.backends.spatialite.operations import SpatiaLiteOperations
from django.utils import six

class DatabaseWrapper(SQLiteDatabaseWrapper):
def __init__(self, *args, **kwargs):
Expand Down Expand Up @@ -50,7 +52,9 @@ def get_new_connection(self, conn_params):
try:
cur.execute("SELECT load_extension(%s)", (self.spatialite_lib,))
except Exception as msg:
raise ImproperlyConfigured('Unable to load the SpatiaLite library extension '
'"%s" because: %s' % (self.spatialite_lib, msg))
new_msg = (
'Unable to load the SpatiaLite library extension '
'"%s" because: %s') % (self.spatialite_lib, msg)
six.reraise(ImproperlyConfigured, ImproperlyConfigured(new_msg), sys.exc_info()[2])
cur.close()
return conn
10 changes: 6 additions & 4 deletions django/contrib/gis/db/backends/spatialite/operations.py
@@ -1,4 +1,5 @@
import re
import sys
from decimal import Decimal

from django.contrib.gis.db.backends.base import BaseSpatialOperations
Expand Down Expand Up @@ -126,10 +127,11 @@ def spatial_version(self):
try:
version = self.spatialite_version_tuple()[1:]
except Exception as msg:
raise ImproperlyConfigured('Cannot determine the SpatiaLite version for the "%s" '
'database (error was "%s"). Was the SpatiaLite initialization '
'SQL loaded on this database?' %
(self.connection.settings_dict['NAME'], msg))
new_msg = (
'Cannot determine the SpatiaLite version for the "%s" '
'database (error was "%s"). Was the SpatiaLite initialization '
'SQL loaded on this database?') % (self.connection.settings_dict['NAME'], msg)
six.reraise(ImproperlyConfigured, ImproperlyConfigured(new_msg), sys.exc_info()[2])
if version < (2, 3, 0):
raise ImproperlyConfigured('GeoDjango only supports SpatiaLite versions '
'2.3.0 and above')
Expand Down
3 changes: 2 additions & 1 deletion django/contrib/gis/utils/layermapping.py
Expand Up @@ -429,7 +429,8 @@ def coord_transform(self):
# Creating the CoordTransform object
return CoordTransform(self.source_srs, target_srs)
except Exception as msg:
raise LayerMapError('Could not translate between the data source and model geometry: %s' % msg)
new_msg = 'Could not translate between the data source and model geometry: %s' % msg
six.reraise(LayerMapError, LayerMapError(new_msg), sys.exc_info()[2])

def geometry_field(self):
"Returns the GeometryField instance associated with the geographic column."
Expand Down
17 changes: 10 additions & 7 deletions django/core/management/commands/flush.py
@@ -1,3 +1,4 @@
import sys
from optparse import make_option

from django.conf import settings
Expand All @@ -8,6 +9,7 @@
from django.core.management.sql import sql_flush, emit_post_sync_signal
from django.utils.importlib import import_module
from django.utils.six.moves import input
from django.utils import six


class Command(NoArgsCommand):
Expand Down Expand Up @@ -62,13 +64,14 @@ def handle_noargs(self, **options):
for sql in sql_list:
cursor.execute(sql)
except Exception as e:
raise CommandError("""Database %s couldn't be flushed. Possible reasons:
* The database isn't running or isn't configured correctly.
* At least one of the expected database tables doesn't exist.
* The SQL was invalid.
Hint: Look at the output of 'django-admin.py sqlflush'. That's the SQL this command wasn't able to run.
The full error: %s""" % (connection.settings_dict['NAME'], e))

new_msg = (
"Database %s couldn't be flushed. Possible reasons:\n"
" * The database isn't running or isn't configured correctly.\n"
" * At least one of the expected database tables doesn't exist.\n"
" * The SQL was invalid.\n"
"Hint: Look at the output of 'django-admin.py sqlflush'. That's the SQL this command wasn't able to run.\n"
"The full error: %s") % (connection.settings_dict['NAME'], e)
six.reraise(CommandError, CommandError(new_msg), sys.exc_info()[2])
# Emit the post sync signal. This allows individual
# applications to respond as if the database had been
# sync'd from scratch.
Expand Down
3 changes: 2 additions & 1 deletion django/core/serializers/json.py
Expand Up @@ -8,6 +8,7 @@
import datetime
import decimal
import json
import sys

from django.core.serializers.base import DeserializationError
from django.core.serializers.python import Serializer as PythonSerializer
Expand Down Expand Up @@ -72,7 +73,7 @@ def Deserializer(stream_or_string, **options):
raise
except Exception as e:
# Map to deserializer error
raise DeserializationError(e)
six.reraise(DeserializationError, DeserializationError(e), sys.exc_info()[2])


class DjangoJSONEncoder(json.JSONEncoder):
Expand Down
3 changes: 2 additions & 1 deletion django/core/serializers/pyyaml.py
Expand Up @@ -6,6 +6,7 @@

import decimal
import yaml
import sys
from io import StringIO

from django.db import models
Expand Down Expand Up @@ -71,4 +72,4 @@ def Deserializer(stream_or_string, **options):
raise
except Exception as e:
# Map to deserializer error
raise DeserializationError(e)
six.reraise(DeserializationError, DeserializationError(e), sys.exc_info()[2])
3 changes: 2 additions & 1 deletion django/core/servers/basehttp.py
Expand Up @@ -24,6 +24,7 @@
from django.core.management.color import color_style
from django.core.wsgi import get_wsgi_application
from django.utils.module_loading import import_by_path
from django.utils import six

__all__ = ['WSGIServer', 'WSGIRequestHandler']

Expand Down Expand Up @@ -121,7 +122,7 @@ def server_bind(self):
try:
super(WSGIServer, self).server_bind()
except Exception as e:
raise WSGIServerException(e)
six.reraise(WSGIServerException, WSGIServerException(e), sys.exc_info()[2])
self.setup_environ()


Expand Down
3 changes: 2 additions & 1 deletion django/forms/fields.py
Expand Up @@ -8,6 +8,7 @@
import datetime
import os
import re
import sys
try:
from urllib.parse import urlsplit, urlunsplit
except ImportError: # Python 2
Expand Down Expand Up @@ -619,7 +620,7 @@ def to_python(self, data):
# raised. Catch and re-raise.
raise
except Exception: # Python Imaging Library doesn't recognize it as an image
raise ValidationError(self.error_messages['invalid_image'])
six.reraise(ValidationError, ValidationError(self.error_messages['invalid_image']), sys.exc_info()[2])
if hasattr(f, 'seek') and callable(f.seek):
f.seek(0)
return f
Expand Down
13 changes: 8 additions & 5 deletions django/forms/util.py
Expand Up @@ -6,6 +6,8 @@
from django.utils.safestring import mark_safe
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from django.utils import six
import sys

# Import ValidationError so that it can be imported from this
# module to maintain backwards compatibility.
Expand Down Expand Up @@ -78,11 +80,12 @@ def from_current_timezone(value):
try:
return timezone.make_aware(value, current_timezone)
except Exception:
raise ValidationError(_('%(datetime)s couldn\'t be interpreted '
'in time zone %(current_timezone)s; it '
'may be ambiguous or it may not exist.')
% {'datetime': value,
'current_timezone': current_timezone})
msg = _(
'%(datetime)s couldn\'t be interpreted '
'in time zone %(current_timezone)s; it '
'may be ambiguous or it may not exist.') % {'datetime': value, 'current_timezone':
current_timezone}
six.reraise(ValidationError, ValidationError(msg), sys.exc_info()[2])
return value

def to_current_timezone(value):
Expand Down
4 changes: 3 additions & 1 deletion django/http/multipartparser.py
Expand Up @@ -8,6 +8,7 @@

import base64
import cgi
import sys

from django.conf import settings
from django.core.exceptions import SuspiciousOperation
Expand Down Expand Up @@ -209,7 +210,8 @@ def parse(self):
chunk = base64.b64decode(chunk)
except Exception as e:
# Since this is only a chunk, any error is an unfixable error.
raise MultiPartParserError("Could not decode base64 data: %r" % e)
msg = "Could not decode base64 data: %r" % e
six.reraise(MultiPartParserError, MultiPartParserError(msg), sys.exc_info()[2])

for i, handler in enumerate(handlers):
chunk_length = len(chunk)
Expand Down
7 changes: 5 additions & 2 deletions django/templatetags/i18n.py
@@ -1,5 +1,6 @@
from __future__ import unicode_literals
import re
import sys

from django.conf import settings
from django.template import (Node, Variable, TemplateSyntaxError,
Expand Down Expand Up @@ -424,8 +425,10 @@ def do_block_translate(parser, token):
value = remaining_bits.pop(0)
value = parser.compile_filter(value)
except Exception:
raise TemplateSyntaxError('"context" in %r tag expected '
'exactly one argument.' % bits[0])
msg = (
'"context" in %r tag expected '
'exactly one argument.') % bits[0]
six.reraise(TemplateSyntaxError, TemplateSyntaxError(msg), sys.exc_info()[2])
else:
raise TemplateSyntaxError('Unknown argument for %r tag: %r.' %
(bits[0], option))
Expand Down
4 changes: 2 additions & 2 deletions django/test/testcases.py
Expand Up @@ -1119,8 +1119,8 @@ def setUpClass(cls):
for port in range(extremes[0], extremes[1] + 1):
possible_ports.append(port)
except Exception:
raise ImproperlyConfigured('Invalid address ("%s") for live '
'server.' % specified_address)
msg = 'Invalid address ("%s") for live server.' % specified_address
six.reraise(ImproperlyConfigured, ImproperlyConfigured(msg), sys.exc_info()[2])
cls.server_thread = LiveServerThread(
host, possible_ports, connections_override)
cls.server_thread.daemon = True
Expand Down
2 changes: 1 addition & 1 deletion django/utils/http.py
Expand Up @@ -144,7 +144,7 @@ def parse_http_date(date):
result = datetime.datetime(year, month, day, hour, min, sec)
return calendar.timegm(result.utctimetuple())
except Exception:
raise ValueError("%r is not a valid date" % date)
six.reraise(ValueError, ValueError("%r is not a valid date" % date), sys.exc_info()[2])

def parse_http_date_safe(date):
"""
Expand Down

0 comments on commit bc4111b

Please sign in to comment.