[gnue] r9803 - in trunk/gnue-common/src: apps base datasources/drivers/other rpc

[email protected]
Newsgroups gmane.comp.cms.gnue.cvs
Message-ID <[email protected]>
Author: johannes
Date: 2007-11-14 08:16:55 -0600 (Wed, 14 Nov 2007)
New Revision: 9803

Added:
   trunk/gnue-common/src/base/errors.py
Modified:
   trunk/gnue-common/src/apps/errors.py
   trunk/gnue-common/src/datasources/drivers/other/appserver.py
   trunk/gnue-common/src/rpc/client.py
Log:
Moved implementation from common.apps.errors into common.base.errors,
more PEP8-ification


Modified: trunk/gnue-common/src/apps/errors.py
===================================================================
--- trunk/gnue-common/src/apps/errors.py	2007-11-14 09:57:51 UTC (rev 9802)
+++ trunk/gnue-common/src/apps/errors.py	2007-11-14 14:16:55 UTC (rev 9803)
@@ -23,6 +23,8 @@
 
 """
 General exception classes.
+
+This module is *DEPRECATED*. Please use gnue.common.base.i18n instead
 """
 
 import sys
@@ -32,13 +34,18 @@
 import exceptions
 
 from gnue.common.base import i18n
+from gnue.common.base import errors
 
+from gnue.common.base.errors import SystemError, AdminError, ApplicationError
+from gnue.common.base.errors import UserError, RemoteError
+
+
 # =============================================================================
 # New basic exception class. Python's standard exception class cannot handle
 # unicode messages.
 # =============================================================================
 
-class gException(Exception):
+class gException(errors.Error):
     """
     The same as the builtin python Exception, but can handle messages that are
     unicode strings.  This exception is available as the builtin class
@@ -55,11 +62,7 @@
       returned by L{getDetail} and L{getException} instead of the traceback.
     """
     def __init__(self, message, group='system'):
-        self.message = message
-        self.group   = group
-        self.name    = None
-        self.detail  = None
-        exceptions.Exception.__init__(self, o(message))
+        errors.Error.__init__(self, message)
 
 
     # -------------------------------------------------------------------------
@@ -88,8 +91,7 @@
         @return: Name of the exception.
         @rtype: Unicode
         """
-        rep = self.name or "%s" % (sys.exc_info()[0] or aType)
-        return self._fmtUnicode(rep.split('.')[-1])
+        return self.get_name(aType)
 
 
     # -------------------------------------------------------------------------
@@ -108,20 +110,9 @@
         @return: Detail information for the exception.
         @rtype: Unicode
         """
-        if self.detail is not None:
-            return self._fmtUnicode(self.detail, i18n.get_encoding())
+        return self.get_detail(count, type, value, trace)
 
-        if sys.exc_info() == (None, None, None):
-            tStack = traceback.format_exception(type, value, trace)
-        else:
-            tStack = traceback.format_exception(*sys.exc_info())
 
-        if count is not None:
-            del tStack[1:count + 1]
-
-        return self._fmtUnicode("%s" % string.join(tStack), i18n.get_encoding())
-
-
     # -------------------------------------------------------------------------
     # Get the message of an exception
     # -------------------------------------------------------------------------
@@ -132,105 +123,9 @@
         @return: Message of the exception.
         @rtype: Unicode
         """
-        return self._fmtUnicode(self.message)
+        return self.message
 
 
-    # -------------------------------------------------------------------------
-    # Make sure a given text is a unicode string
-    # -------------------------------------------------------------------------
-
-    def _fmtUnicode(self, text, encoding=None):
-        """
-        Return a given text as unicode string using an optional encoding or the
-        system's default encoding.
-
-        @param text: String to be encoded. If this string is already unicode no
-          modification will take place.
-        @param encoding: Encoding to use (if None, system default encoding will
-          take place)
-        @return: Unicode representation of the text parameter.
-        """
-        if isinstance(text, types.UnicodeType):
-            return text
-        else:
-            if encoding is not None:
-                return unicode(text, encoding, 'replace')
-            else:
-                return unicode(text, errors='replace')
-
-
-# =============================================================================
-# System Error
-# =============================================================================
-
-class SystemError(gException):
-    """
-    This exception class should be used for exceptions indicating a bug in
-    GNUe.  Whenever such an exception is raised, one have found such a bug :)
-    """
-    def __init__(self, message):
-        gException.__init__(self, message, 'system')
-
-
-# =============================================================================
-# Administrative Errors
-# =============================================================================
-
-class AdminError(gException):
-    """
-    This exception class should be used for exceptions indicating a
-    misconfiguration in a widest sense. This could be a missing module for a
-    dbdriver as well as an 'out of disk space' error.
-    """
-    def __init__(self, message):
-        gException.__init__(self, message, 'admin')
-
-
-# =============================================================================
-# Application Errors
-# =============================================================================
-
-class ApplicationError(gException):
-    """
-    This class should be used for errors caused by applications like a corrupt
-    trigger code, or a misformed xml-file and so on.
-    """
-    def __init__(self, message):
-        gException.__init__(self, message, 'application')
-
-
-# =============================================================================
-# User Errors
-# =============================================================================
-
-class UserError(gException):
-    """
-    This class should be used for exceptions where a user did something wrong,
-    or a situation has occured which isn't dramatic, but the user has to be
-    informed of. Example: wrong password or the user has entered non-numeric
-    data into a numeric field, and so on.
-    """
-    def __init__(self, message):
-        gException.__init__(self, message, 'user')
-
-
-# =============================================================================
-# Exceptions raised on a remote site/process
-# =============================================================================
-
-class RemoteError(gException):
-    """
-    This class is used for transporting an exception raised at a remote point.
-    Once it has been created it never changes it's contents. A remote error
-    usually contains System-, Admin- or User-Errors.
-    """
-    def __init__(self, group, name, message, detail):
-        gException.__init__(self, message)
-        self.group  = group
-        self.name   = name
-        self.detail = detail
-
-
 # -----------------------------------------------------------------------------
 # Get a tuple (type, name, message, detail) for the last exception raised
 # -----------------------------------------------------------------------------
@@ -249,25 +144,4 @@
     @param count: number of lines to skip in the traceback
     @return: tuple with group, name, message and detail of the last exception.
     """
-    (sType, sValue, sTrace) = sys.exc_info()
-    aType  = aType  or sType
-    aValue = aValue or sValue
-    aTrace = aTrace or sTrace
-
-    if isinstance(aValue, gException):
-        return (aValue.getGroup(), aValue.getName(aType), aValue.getMessage(),
-                aValue.getDetail(count, aType, aValue, aTrace))
-    else:
-        # Exception was not a descendant of gException, so we construct the
-        # tuple from the exception information
-        lines = traceback.format_exception(aType, aValue, aTrace)
-        if count is not None:
-            del lines[1:count + 1]
-
-        name = unicode("%s" % aType, i18n.get_encoding(), 'replace')
-        name = name.split('.')[-1]
-        message = unicode("%s" % aValue, i18n.get_encoding(), 'replace')
-        detail  = string.join(lines)
-        if isinstance(detail, types.StringType):
-            detail = unicode(detail, i18n.get_encoding(), 'replace')
-        return ('system', name, message, detail)
+    return errors.get_exception(count, aType, aValue, aTrace)

Added: trunk/gnue-common/src/base/errors.py
===================================================================
--- trunk/gnue-common/src/base/errors.py	2007-11-14 09:57:51 UTC (rev 9802)
+++ trunk/gnue-common/src/base/errors.py	2007-11-14 14:16:55 UTC (rev 9803)
@@ -0,0 +1,253 @@
+# GNU Enterprise Common Library - Base exception classes
+#
+# Copyright 2001-2007 Free Software Foundation
+#
+# This file is part of GNU Enterprise
+#
+# GNU Enterprise is free software; you can redistribute it
+# and/or modify it under the terms of the GNU General Public
+# License as published by the Free Software Foundation; either
+# version 2, or (at your option) any later version.
+#
+# GNU Enterprise is distributed in the hope that it will be
+# useful, but WITHOUT ANY WARRANTY; without even the implied
+# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+# PURPOSE. See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public
+# License along with program; see the file COPYING. If not,
+# write to the Free Software Foundation, Inc., 59 Temple Place
+# - Suite 330, Boston, MA 02111-1307, USA.
+#
+# $Id$
+
+"""
+General exception classes.
+"""
+
+import sys
+import traceback
+import exceptions
+
+from gnue.common.base import i18n
+
+__all__ = ['get_exception', 'SystemError', 'AdminError', 'ApplicationError',
+           'UserError', 'RemoteError']
+
+
+# =============================================================================
+# Base exception class for all GNUe Exceptions
+# =============================================================================
+
+class Error(exceptions.Exception):
+    """
+    The same as the builtin python Exception, but can handle messages that are
+    unicode strings.  All other user-defined exceptions should be derived from
+    this class.
+
+    @ivar message: The error message.
+    @type message: Unicode
+    @ivar group: The group or category of the exception. Can be one of 'system',
+        'admin', 'application', or 'user'.
+    @ivar name: The name of the exception. If set, this will be returned by
+        L{get_name} and L{get_exception} instead of the class name of the
+        exception.
+    @ivar detail: The detail information to the exception. If set, this will be
+        returned by L{get_detail} and L{get_exception} instead of the
+        traceback.
+    """
+    def __init__(self, message, group='system'):
+
+        self.message = message
+        self.group   = group
+        self.name    = None
+        self.detail  = None
+
+        exceptions.Exception.__init__(self, o(message))
+
+
+    # -------------------------------------------------------------------------
+    # Return the name of the exception
+    # -------------------------------------------------------------------------
+
+    def get_name(self, exc_type=None):
+        """
+        Return the exception's name, which is the classname of the exception
+        class unless overwritten with L{name}.
+
+        @param exc_type: Type of the exception class to be used if no name is
+            defined and the exception being handled is no longer available in
+            sys.exc_info()
+
+        @return: Name of the exception.
+        @rtype: Unicode
+        """
+        rep = self.name or "%s" % (sys.exc_info()[0] or exc_type)
+        return to_unicode(rep.split('.')[-1])
+
+
+    # -------------------------------------------------------------------------
+    # Get the detail of an exception
+    # -------------------------------------------------------------------------
+
+    def get_detail(self, count=None, etype=None, evalue=None, etrace=None):
+        """
+        Return the exception's detail, which is the traceback unless
+        overwritten with L{detail}.
+
+        Optionally, a number of lines can be skipped at the beginning of the
+        traceback (if the detail I{is} the traceback).
+
+        @param count: Number of lines to skip at the beginning of the traceback.
+        @return: Detail information for the exception.
+        @rtype: Unicode
+        """
+        if self.detail is not None:
+            return to_unicode(self.detail, i18n.get_encoding())
+
+        (stype, svalue, strace) = sys.exc_info()
+        stype  = stype or etype
+        svalue = svalue or evalue
+        strace = strace or etrace
+
+        tStack = traceback.format_exception(stype, svalue, strace)
+        if count is not None:
+            del tStack[1:count + 1]
+
+        return to_unicode("%s" % ''.join(tStack), i18n.get_encoding())
+
+
+
+# =============================================================================
+# System Error
+# =============================================================================
+
+class SystemError(Error):
+    """
+    This exception class should be used for exceptions indicating a bug in
+    GNUe.  Whenever such an exception is raised, one have found such a bug :)
+    """
+    def __init__(self, message):
+        Error.__init__(self, message, 'system')
+
+
+# =============================================================================
+# Administrative Errors
+# =============================================================================
+
+class AdminError(Error):
+    """
+    This exception class should be used for exceptions indicating a
+    misconfiguration in a widest sense. This could be a missing module for a
+    dbdriver as well as an 'out of disk space' error.
+    """
+    def __init__(self, message):
+        Error.__init__(self, message, 'admin')
+
+
+# =============================================================================
+# Application Errors
+# =============================================================================
+
+class ApplicationError(Error):
+    """
+    This class should be used for errors caused by applications like a corrupt
+    trigger code, or a misformed xml-file and so on.
+    """
+    def __init__(self, message):
+        Error.__init__(self, message, 'application')
+
+
+# =============================================================================
+# User Errors
+# =============================================================================
+
+class UserError(Error):
+    """
+    This class should be used for exceptions where a user did something wrong,
+    or a situation has occured which isn't dramatic, but the user has to be
+    informed of. Example: wrong password or the user has entered non-numeric
+    data into a numeric field, and so on.
+    """
+    def __init__(self, message):
+        Error.__init__(self, message, 'user')
+
+
+# =============================================================================
+# Exceptions raised on a remote site/process
+# =============================================================================
+
+class RemoteError(Error):
+    """
+    This class is used for transporting an exception raised at a remote point.
+    Once it has been created it never changes it's contents. A remote error
+    usually contains System-, Admin- or User-Errors.
+    """
+    def __init__(self, group, name, message, detail):
+        Error.__init__(self, message)
+        self.group  = group
+        self.name   = name
+        self.detail = detail
+
+
+# -----------------------------------------------------------------------------
+# Get a tuple (type, name, message, detail) for the last exception raised
+# -----------------------------------------------------------------------------
+
+def get_exception(count=None, exc_type=None, exc_value=None, exc_tback=None):
+    """
+    Return textual information about an exception.
+
+    This function creates a tuple (group, name, message, detail) for the last
+    exception raised. The optional parameter determines the number of lines
+    skipped from the detail traceback.
+
+    The intended use of this function is to get the text to be displayed in
+    error messages.
+
+    @param count: number of lines to skip in the traceback
+    @return: tuple with group, name, message and detail of the last exception.
+    """
+    (sType, sValue, sTrace) = sys.exc_info()
+
+    exc_type  = exc_type  or sType
+    exc_value = exc_value or sValue
+    exc_tback = exc_tback or sTrace
+
+    if isinstance(exc_value, Error):
+        return (exc_value.group,
+                exc_value.get_name(exc_type),
+                exc_value.message,
+                exc_value.get_detail(count, exc_type, exc_value, exc_tback))
+    else:
+        # Exception was not a descendant of Error, so we construct the
+        # tuple from the exception information
+        lines = traceback.format_exception(exc_type, exc_value, exc_tback)
+        if count is not None:
+            del lines[1:count + 1]
+
+        name = unicode("%s" % exc_type, i18n.get_encoding(), 'replace')
+        name = name.split('.')[-1]
+        message = unicode("%s" % exc_value, i18n.get_encoding(), 'replace')
+        detail  = ''.join(lines)
+        if isinstance(detail, str):
+            detail = unicode(detail, i18n.get_encoding(), 'replace')
+
+        return ('system', name, message, detail)
+
+
+# -----------------------------------------------------------------------------
+# Create a unicode string using a given encoding
+# -----------------------------------------------------------------------------
+
+def to_unicode(text, encoding=None):
+
+    result = text
+
+    if isinstance(text, str):
+        if encoding is not None:
+            result = unicode(text, encoding, 'replace')
+        else:
+            result = unicode(text, errors='replace')
+
+    return result


Property changes on: trunk/gnue-common/src/base/errors.py
___________________________________________________________________
Name: svn:keywords
   + Id

Modified: trunk/gnue-common/src/datasources/drivers/other/appserver.py
===================================================================
--- trunk/gnue-common/src/datasources/drivers/other/appserver.py	2007-11-14 09:57:51 UTC (rev 9802)
+++ trunk/gnue-common/src/datasources/drivers/other/appserver.py	2007-11-14 14:16:55 UTC (rev 9803)
@@ -385,8 +385,8 @@
       self._session = self._sm.open (connectData)
 
     except errors.RemoteError, e:
-      if e.getName () == 'AuthError':
-        raise Exceptions.LoginError, e.getMessage ()
+      if e.get_name() == 'AuthError':
+        raise Exceptions.LoginError, e.message
       else:
         raise
 

Modified: trunk/gnue-common/src/rpc/client.py
===================================================================
--- trunk/gnue-common/src/rpc/client.py	2007-11-14 09:57:51 UTC (rev 9802)
+++ trunk/gnue-common/src/rpc/client.py	2007-11-14 14:16:55 UTC (rev 9803)
@@ -163,22 +163,16 @@
 
   except Exception, e:
     print "-" * 70
-    if isinstance (e, errors.gException):
-      print "Exception Group:", e.getGroup ()
-      print "Exception Name :", e.getName ()
-      print "Message        :", e.getMessage ()
-    else:
-      print "Exception:", e
+    (group, name, message, detail) = errors.getException()
+    print "Exception Group:", group
+    print "Exception Name :", name
+    print "Message        :", message
+    print "Detail         :", detail
 
     print "-" * 70
     print "local traceback:"
     traceback.print_exc ()
 
-    if isinstance (e, errors.gException):
-      print "-" * 70
-      print "remote exception detail:", e.getDetail ()
-      print "-" * 70
-
   print "-" * 70
   o = None
   print "Sending %r (%s) to a roundtrip ..." % (o, type (o))
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.