Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Fixed #18003 -- Preserved tracebacks when re-raising errors.

Thanks jrothenbuhler for draft patch, Konark Modi for updates.
  • Loading branch information...
commit bc4111ba68e5eede1f68882a16d68441a845e30b 1 parent 1fe90b2
Konark Modi authored March 19, 2013 carljm committed March 19, 2013
3  django/contrib/admin/views/main.py
... ...
@@ -1,4 +1,5 @@
1 1
 import operator
  2
+import sys
2 3
 import warnings
3 4
 from functools import reduce
4 5
 
@@ -173,7 +174,7 @@ def get_filters(self, request):
173 174
                                 lookup_needs_distinct(self.lookup_opts, key))
174 175
             return filter_specs, bool(filter_specs), lookup_params, use_distinct
175 176
         except FieldDoesNotExist as e:
176  
-            raise IncorrectLookupParameters(e)
  177
+            six.reraise(IncorrectLookupParameters, IncorrectLookupParameters(e), sys.exc_info()[2])
177 178
 
178 179
     def get_query_string(self, new_params=None, remove=None):
179 180
         if new_params is None: new_params = {}
9  django/contrib/gis/db/backends/oracle/introspection.py
... ...
@@ -1,5 +1,7 @@
1 1
 import cx_Oracle
  2
+import sys
2 3
 from django.db.backends.oracle.introspection import DatabaseIntrospection
  4
+from django.utils import six
3 5
 
4 6
 class OracleIntrospection(DatabaseIntrospection):
5 7
     # Associating any OBJECTVAR instances with GeometryField.  Of course,
@@ -17,8 +19,11 @@ def get_geometry_type(self, table_name, geo_col):
17 19
                                (table_name.upper(), geo_col.upper()))
18 20
                 row = cursor.fetchone()
19 21
             except Exception as msg:
20  
-                raise Exception('Could not find entry in USER_SDO_GEOM_METADATA corresponding to "%s"."%s"\n'
21  
-                                'Error message: %s.' % (table_name, geo_col, msg))
  22
+                new_msg = (
  23
+                    'Could not find entry in USER_SDO_GEOM_METADATA '
  24
+                    'corresponding to "%s"."%s"\n'
  25
+                    'Error message: %s.') % (table_name, geo_col, msg)
  26
+                six.reraise(Exception, Exception(new_msg), sys.exc_info()[2])
22 27
 
23 28
             # TODO: Research way to find a more specific geometry field type for
24 29
             # the column's contents.
8  django/contrib/gis/db/backends/spatialite/base.py
... ...
@@ -1,3 +1,4 @@
  1
+import sys
1 2
 from ctypes.util import find_library
2 3
 from django.conf import settings
3 4
 
@@ -8,6 +9,7 @@
8 9
 from django.contrib.gis.db.backends.spatialite.creation import SpatiaLiteCreation
9 10
 from django.contrib.gis.db.backends.spatialite.introspection import SpatiaLiteIntrospection
10 11
 from django.contrib.gis.db.backends.spatialite.operations import SpatiaLiteOperations
  12
+from django.utils import six
11 13
 
12 14
 class DatabaseWrapper(SQLiteDatabaseWrapper):
13 15
     def __init__(self, *args, **kwargs):
@@ -50,7 +52,9 @@ def get_new_connection(self, conn_params):
50 52
         try:
51 53
             cur.execute("SELECT load_extension(%s)", (self.spatialite_lib,))
52 54
         except Exception as msg:
53  
-            raise ImproperlyConfigured('Unable to load the SpatiaLite library extension '
54  
-                                       '"%s" because: %s' % (self.spatialite_lib, msg))
  55
+            new_msg = (
  56
+                'Unable to load the SpatiaLite library extension '
  57
+                '"%s" because: %s') % (self.spatialite_lib, msg)
  58
+            six.reraise(ImproperlyConfigured, ImproperlyConfigured(new_msg), sys.exc_info()[2])
55 59
         cur.close()
56 60
         return conn
10  django/contrib/gis/db/backends/spatialite/operations.py
... ...
@@ -1,4 +1,5 @@
1 1
 import re
  2
+import sys
2 3
 from decimal import Decimal
3 4
 
4 5
 from django.contrib.gis.db.backends.base import BaseSpatialOperations
@@ -126,10 +127,11 @@ def spatial_version(self):
126 127
         try:
127 128
             version = self.spatialite_version_tuple()[1:]
128 129
         except Exception as msg:
129  
-            raise ImproperlyConfigured('Cannot determine the SpatiaLite version for the "%s" '
130  
-                                       'database (error was "%s").  Was the SpatiaLite initialization '
131  
-                                       'SQL loaded on this database?' %
132  
-                                       (self.connection.settings_dict['NAME'], msg))
  130
+            new_msg = (
  131
+                'Cannot determine the SpatiaLite version for the "%s" '
  132
+                'database (error was "%s").  Was the SpatiaLite initialization '
  133
+                'SQL loaded on this database?') % (self.connection.settings_dict['NAME'], msg)
  134
+            six.reraise(ImproperlyConfigured, ImproperlyConfigured(new_msg), sys.exc_info()[2])
133 135
         if version < (2, 3, 0):
134 136
             raise ImproperlyConfigured('GeoDjango only supports SpatiaLite versions '
135 137
                                        '2.3.0 and above')
3  django/contrib/gis/utils/layermapping.py
@@ -429,7 +429,8 @@ def coord_transform(self):
429 429
             # Creating the CoordTransform object
430 430
             return CoordTransform(self.source_srs, target_srs)
431 431
         except Exception as msg:
432  
-            raise LayerMapError('Could not translate between the data source and model geometry: %s' % msg)
  432
+            new_msg = 'Could not translate between the data source and model geometry: %s' % msg
  433
+            six.reraise(LayerMapError, LayerMapError(new_msg), sys.exc_info()[2])
433 434
 
434 435
     def geometry_field(self):
435 436
         "Returns the GeometryField instance associated with the geographic column."
17  django/core/management/commands/flush.py
... ...
@@ -1,3 +1,4 @@
  1
+import sys
1 2
 from optparse import make_option
2 3
 
3 4
 from django.conf import settings
@@ -8,6 +9,7 @@
8 9
 from django.core.management.sql import sql_flush, emit_post_sync_signal
9 10
 from django.utils.importlib import import_module
10 11
 from django.utils.six.moves import input
  12
+from django.utils import six
11 13
 
12 14
 
13 15
 class Command(NoArgsCommand):
@@ -62,13 +64,14 @@ def handle_noargs(self, **options):
62 64
                     for sql in sql_list:
63 65
                         cursor.execute(sql)
64 66
             except Exception as e:
65  
-                raise CommandError("""Database %s couldn't be flushed. Possible reasons:
66  
-  * The database isn't running or isn't configured correctly.
67  
-  * At least one of the expected database tables doesn't exist.
68  
-  * The SQL was invalid.
69  
-Hint: Look at the output of 'django-admin.py sqlflush'. That's the SQL this command wasn't able to run.
70  
-The full error: %s""" % (connection.settings_dict['NAME'], e))
71  
-
  67
+                new_msg = (
  68
+                    "Database %s couldn't be flushed. Possible reasons:\n"
  69
+                    "  * The database isn't running or isn't configured correctly.\n"
  70
+                    "  * At least one of the expected database tables doesn't exist.\n"
  71
+                    "  * The SQL was invalid.\n"
  72
+                    "Hint: Look at the output of 'django-admin.py sqlflush'. That's the SQL this command wasn't able to run.\n"
  73
+                    "The full error: %s") % (connection.settings_dict['NAME'], e)
  74
+                six.reraise(CommandError, CommandError(new_msg), sys.exc_info()[2])
72 75
             # Emit the post sync signal. This allows individual
73 76
             # applications to respond as if the database had been
74 77
             # sync'd from scratch.
3  django/core/serializers/json.py
@@ -8,6 +8,7 @@
8 8
 import datetime
9 9
 import decimal
10 10
 import json
  11
+import sys
11 12
 
12 13
 from django.core.serializers.base import DeserializationError
13 14
 from django.core.serializers.python import Serializer as PythonSerializer
@@ -72,7 +73,7 @@ def Deserializer(stream_or_string, **options):
72 73
         raise
73 74
     except Exception as e:
74 75
         # Map to deserializer error
75  
-        raise DeserializationError(e)
  76
+        six.reraise(DeserializationError, DeserializationError(e), sys.exc_info()[2])
76 77
 
77 78
 
78 79
 class DjangoJSONEncoder(json.JSONEncoder):
3  django/core/serializers/pyyaml.py
@@ -6,6 +6,7 @@
6 6
 
7 7
 import decimal
8 8
 import yaml
  9
+import sys
9 10
 from io import StringIO
10 11
 
11 12
 from django.db import models
@@ -71,4 +72,4 @@ def Deserializer(stream_or_string, **options):
71 72
         raise
72 73
     except Exception as e:
73 74
         # Map to deserializer error
74  
-        raise DeserializationError(e)
  75
+        six.reraise(DeserializationError, DeserializationError(e), sys.exc_info()[2])
3  django/core/servers/basehttp.py
@@ -24,6 +24,7 @@
24 24
 from django.core.management.color import color_style
25 25
 from django.core.wsgi import get_wsgi_application
26 26
 from django.utils.module_loading import import_by_path
  27
+from django.utils import six
27 28
 
28 29
 __all__ = ['WSGIServer', 'WSGIRequestHandler']
29 30
 
@@ -121,7 +122,7 @@ def server_bind(self):
121 122
         try:
122 123
             super(WSGIServer, self).server_bind()
123 124
         except Exception as e:
124  
-            raise WSGIServerException(e)
  125
+            six.reraise(WSGIServerException, WSGIServerException(e), sys.exc_info()[2])
125 126
         self.setup_environ()
126 127
 
127 128
 
3  django/forms/fields.py
@@ -8,6 +8,7 @@
8 8
 import datetime
9 9
 import os
10 10
 import re
  11
+import sys
11 12
 try:
12 13
     from urllib.parse import urlsplit, urlunsplit
13 14
 except ImportError:     # Python 2
@@ -619,7 +620,7 @@ def to_python(self, data):
619 620
             # raised. Catch and re-raise.
620 621
             raise
621 622
         except Exception: # Python Imaging Library doesn't recognize it as an image
622  
-            raise ValidationError(self.error_messages['invalid_image'])
  623
+            six.reraise(ValidationError, ValidationError(self.error_messages['invalid_image']), sys.exc_info()[2])
623 624
         if hasattr(f, 'seek') and callable(f.seek):
624 625
             f.seek(0)
625 626
         return f
13  django/forms/util.py
@@ -6,6 +6,8 @@
6 6
 from django.utils.safestring import mark_safe
7 7
 from django.utils import timezone
8 8
 from django.utils.translation import ugettext_lazy as _
  9
+from django.utils import six
  10
+import sys
9 11
 
10 12
 # Import ValidationError so that it can be imported from this
11 13
 # module to maintain backwards compatibility.
@@ -78,11 +80,12 @@ def from_current_timezone(value):
78 80
         try:
79 81
             return timezone.make_aware(value, current_timezone)
80 82
         except Exception:
81  
-            raise ValidationError(_('%(datetime)s couldn\'t be interpreted '
82  
-                                    'in time zone %(current_timezone)s; it '
83  
-                                    'may be ambiguous or it may not exist.')
84  
-                                  % {'datetime': value,
85  
-                                     'current_timezone': current_timezone})
  83
+            msg = _(
  84
+                '%(datetime)s couldn\'t be interpreted '
  85
+                'in time zone %(current_timezone)s; it '
  86
+                'may be ambiguous or it may not exist.') % {'datetime': value, 'current_timezone':
  87
+                current_timezone}
  88
+            six.reraise(ValidationError, ValidationError(msg), sys.exc_info()[2])
86 89
     return value
87 90
 
88 91
 def to_current_timezone(value):
4  django/http/multipartparser.py
@@ -8,6 +8,7 @@
8 8
 
9 9
 import base64
10 10
 import cgi
  11
+import sys
11 12
 
12 13
 from django.conf import settings
13 14
 from django.core.exceptions import SuspiciousOperation
@@ -209,7 +210,8 @@ def parse(self):
209 210
                                     chunk = base64.b64decode(chunk)
210 211
                                 except Exception as e:
211 212
                                     # Since this is only a chunk, any error is an unfixable error.
212  
-                                    raise MultiPartParserError("Could not decode base64 data: %r" % e)
  213
+                                    msg = "Could not decode base64 data: %r" % e
  214
+                                    six.reraise(MultiPartParserError, MultiPartParserError(msg), sys.exc_info()[2])
213 215
 
214 216
                             for i, handler in enumerate(handlers):
215 217
                                 chunk_length = len(chunk)
7  django/templatetags/i18n.py
... ...
@@ -1,5 +1,6 @@
1 1
 from __future__ import unicode_literals
2 2
 import re
  3
+import sys
3 4
 
4 5
 from django.conf import settings
5 6
 from django.template import (Node, Variable, TemplateSyntaxError,
@@ -424,8 +425,10 @@ def do_block_translate(parser, token):
424 425
                 value = remaining_bits.pop(0)
425 426
                 value = parser.compile_filter(value)
426 427
             except Exception:
427  
-                raise TemplateSyntaxError('"context" in %r tag expected '
428  
-                                          'exactly one argument.' % bits[0])
  428
+                msg = (
  429
+                    '"context" in %r tag expected '
  430
+                    'exactly one argument.') % bits[0]
  431
+                six.reraise(TemplateSyntaxError, TemplateSyntaxError(msg), sys.exc_info()[2])
429 432
         else:
430 433
             raise TemplateSyntaxError('Unknown argument for %r tag: %r.' %
431 434
                                       (bits[0], option))
4  django/test/testcases.py
@@ -1119,8 +1119,8 @@ def setUpClass(cls):
1119 1119
                     for port in range(extremes[0], extremes[1] + 1):
1120 1120
                         possible_ports.append(port)
1121 1121
         except Exception:
1122  
-            raise ImproperlyConfigured('Invalid address ("%s") for live '
1123  
-                'server.' % specified_address)
  1122
+            msg = 'Invalid address ("%s") for live server.' % specified_address
  1123
+            six.reraise(ImproperlyConfigured, ImproperlyConfigured(msg), sys.exc_info()[2])
1124 1124
         cls.server_thread = LiveServerThread(
1125 1125
             host, possible_ports, connections_override)
1126 1126
         cls.server_thread.daemon = True
2  django/utils/http.py
@@ -144,7 +144,7 @@ def parse_http_date(date):
144 144
         result = datetime.datetime(year, month, day, hour, min, sec)
145 145
         return calendar.timegm(result.utctimetuple())
146 146
     except Exception:
147  
-        raise ValueError("%r is not a valid date" % date)
  147
+        six.reraise(ValueError, ValueError("%r is not a valid date" % date), sys.exc_info()[2])
148 148
 
149 149
 def parse_http_date_safe(date):
150 150
     """

0 notes on commit bc4111b

Please sign in to comment.
Something went wrong with that request. Please try again.