[FIX] P3: exceptions compatibility changes
* exceptions have lost their ``message`` attribute * ``raise type, value, tb`` has been removed so add a compatibility shim to pycompat to raise a new exception with an existing traceback
This commit is contained in:
@@ -38,7 +38,7 @@ class AuthSignupHome(Home):
|
||||
if request.env["res.users"].sudo().search([("login", "=", qcontext.get("login"))]):
|
||||
qcontext["error"] = _("Another user is already registered using this email address.")
|
||||
else:
|
||||
_logger.error(e.message)
|
||||
_logger.error("%s", e)
|
||||
qcontext['error'] = _("Could not create a new account.")
|
||||
|
||||
return request.render('auth_signup.signup', qcontext)
|
||||
@@ -64,7 +64,7 @@ class AuthSignupHome(Home):
|
||||
qcontext['error'] = _("Could not reset your password")
|
||||
_logger.exception('error when resetting password')
|
||||
except Exception as e:
|
||||
qcontext['error'] = e.message or e.name
|
||||
qcontext['error'] = str(e)
|
||||
|
||||
response = request.render('auth_signup.reset_password', qcontext)
|
||||
response.headers['X-Frame-Options'] = 'DENY'
|
||||
|
||||
@@ -617,9 +617,9 @@ class Import(models.TransientModel):
|
||||
try:
|
||||
line[index] = dt.strftime(dt.strptime(ustr(line[index]).encode('utf-8'), user_format), server_format)
|
||||
except ValueError as e:
|
||||
raise ValueError(_("Column %s contains incorrect values. Error in line %d: %s") % (name, num + 1, ustr(e.message)))
|
||||
raise ValueError(_("Column %s contains incorrect values. Error in line %d: %s") % (name, num + 1, e))
|
||||
except Exception as e:
|
||||
raise ValueError(_("Error Parsing Date [%s:L%d]: %s") % (name, num + 1, ustr(e.message)))
|
||||
raise ValueError(_("Error Parsing Date [%s:L%d]: %s") % (name, num + 1, e))
|
||||
|
||||
elif field['type'] in ('float', 'monetary') and name in import_fields:
|
||||
# Parse float, sometimes float values from file have currency symbol or () to denote a negative value
|
||||
|
||||
@@ -87,7 +87,9 @@ class GoalDefinition(models.Model):
|
||||
# dummy search to make sure the domain is valid
|
||||
Obj.search_count(domain)
|
||||
except (ValueError, SyntaxError) as e:
|
||||
msg = e.message or (e.msg + '\n' + e.text)
|
||||
msg = e
|
||||
if isinstance(e, SyntaxError):
|
||||
msg = (e.msg + '\n' + e.text)
|
||||
raise exceptions.UserError(_("The domain for the definition %s seems incorrect, please check it.\n\n%s") % (definition.name, msg))
|
||||
return True
|
||||
|
||||
@@ -105,7 +107,7 @@ class GoalDefinition(models.Model):
|
||||
_("The model configuration for the definition %s seems incorrect, please check it.\n\n%s not stored") % (definition.name, definition.field_id.name))
|
||||
except KeyError as e:
|
||||
raise exceptions.UserError(
|
||||
_("The model configuration for the definition %s seems incorrect, please check it.\n\n%s not found") % (definition.name, e.message))
|
||||
_("The model configuration for the definition %s seems incorrect, please check it.\n\n%s not found") % (definition.name, e))
|
||||
|
||||
@api.model
|
||||
def create(self, vals):
|
||||
|
||||
@@ -802,7 +802,7 @@ class GoogleCalendar(models.AbstractModel):
|
||||
if actSrc == 'GG':
|
||||
self.create_from_google(event, my_partner_id)
|
||||
elif actSrc == 'OE':
|
||||
raise "Should be never here, creation for OE is done before update !"
|
||||
raise AssertionError("Should be never here, creation for OE is done before update !")
|
||||
#TODO Add to batch
|
||||
elif isinstance(actToDo, Update):
|
||||
if actSrc == 'GG':
|
||||
|
||||
@@ -81,7 +81,7 @@ class EscposDriver(Thread):
|
||||
try:
|
||||
description = usb.util.get_string(printer, 256, printer.iManufacturer) + " " + usb.util.get_string(printer, 256, printer.iProduct)
|
||||
except Exception as e:
|
||||
_logger.error("Can not get printer description: %s" % (e.message or repr(e)))
|
||||
_logger.error("Can not get printer description: %s" % e)
|
||||
description = 'Unknown printer'
|
||||
connected.append({
|
||||
'vendor': printer.idVendor,
|
||||
|
||||
@@ -326,7 +326,7 @@ class MailMail(models.Model):
|
||||
res = IrMailServer.send_email(
|
||||
msg, mail_server_id=mail.mail_server_id.id, smtp_session=smtp_session)
|
||||
except AssertionError as error:
|
||||
if error.message == IrMailServer.NO_VALID_RECIPIENT:
|
||||
if str(error) == IrMailServer.NO_VALID_RECIPIENT:
|
||||
# No valid recipient found for this particular
|
||||
# mail item -> ignore error to avoid blocking
|
||||
# delivery to next recipients, if any. If this is
|
||||
|
||||
@@ -41,7 +41,7 @@ class OgoneController(http.Controller):
|
||||
acq.s2s_process(post)
|
||||
except Exception as e:
|
||||
# synthax error: 'CHECK ERROR: |Not a valid date\n\n50001111: None'
|
||||
error = e.message.splitlines()[0].split('|')[-1] or ''
|
||||
error = str(e).splitlines()[0].split('|')[-1] or ''
|
||||
return werkzeug.utils.redirect(post.get('return_url', '/') + (error and '#error=%s' % werkzeug.url_quote(error) or ''))
|
||||
|
||||
@http.route(['/payment/ogone/s2s/feedback'], auth='none', csrf=False)
|
||||
|
||||
@@ -1053,7 +1053,7 @@ class Binary(http.Controller):
|
||||
args = [len(data), ufile.filename,
|
||||
ufile.content_type, base64.b64encode(data)]
|
||||
except Exception as e:
|
||||
args = [False, e.message]
|
||||
args = [False, str(e)]
|
||||
return out % (json.dumps(callback), json.dumps(args))
|
||||
|
||||
@http.route('/web/binary/upload_attachment', type='http', auth="user")
|
||||
@@ -1647,4 +1647,4 @@ class ReportController(http.Controller):
|
||||
|
||||
@http.route(['/report/check_wkhtmltopdf'], type='json', auth="user")
|
||||
def check_wkhtmltopdf(self):
|
||||
return request.env['ir.actions.report'].get_wkhtmltopdf_state()
|
||||
return request.env['ir.actions.report'].get_wkhtmltopdf_state()
|
||||
|
||||
@@ -319,7 +319,7 @@ class WebsiteSlides(http.Controller):
|
||||
return {'error': e.name}
|
||||
except Exception as e:
|
||||
_logger.error(e)
|
||||
return {'error': _('Internal server error, please try again later or contact administrator.\nHere is the error message: %s') % e.message}
|
||||
return {'error': _('Internal server error, please try again later or contact administrator.\nHere is the error message: %s') % e}
|
||||
return {'url': "/slides/slide/%s" % (slide_id.id)}
|
||||
|
||||
# --------------------------------------------------
|
||||
|
||||
@@ -356,6 +356,6 @@ def convert_exception_to(to_type, with_message=False):
|
||||
else:
|
||||
message = str(with_message)
|
||||
|
||||
raise to_type, message, tb
|
||||
raise pycompat.reraise(to_type, to_type(message), tb)
|
||||
except to_type as e:
|
||||
return e
|
||||
|
||||
@@ -406,7 +406,7 @@ class IrModelFields(models.Model):
|
||||
try:
|
||||
field = self._related_field()
|
||||
except UserError as e:
|
||||
return {'warning': {'title': _("Warning"), 'message': e.message}}
|
||||
return {'warning': {'title': _("Warning"), 'message': e}}
|
||||
self.ttype = field.type
|
||||
self.relation = field.comodel_name
|
||||
self.readonly = True
|
||||
|
||||
@@ -524,7 +524,7 @@ class JavascriptAsset(WebAsset):
|
||||
try:
|
||||
return super(JavascriptAsset, self)._fetch_content()
|
||||
except AssetError as e:
|
||||
return "console.error(%s);" % json.dumps(e.message)
|
||||
return "console.error(%s);" % json.dumps(str(e))
|
||||
|
||||
def to_html(self):
|
||||
if self.url:
|
||||
@@ -573,7 +573,7 @@ class StylesheetAsset(WebAsset):
|
||||
|
||||
return content
|
||||
except AssetError as e:
|
||||
self.bundle.css_errors.append(e.message)
|
||||
self.bundle.css_errors.append(str(e))
|
||||
return ''
|
||||
|
||||
def minify(self):
|
||||
|
||||
@@ -127,7 +127,7 @@ class IrQWeb(models.AbstractModel, QWeb):
|
||||
def _compile_directive_call_assets(self, el, options):
|
||||
""" This special 't-call' tag can be used in order to aggregate/minify javascript and css assets"""
|
||||
if len(el):
|
||||
raise "t-call-assets cannot contain children nodes"
|
||||
raise SyntaxError("t-call-assets cannot contain children nodes")
|
||||
|
||||
# self._get_asset(xmlid, options, css=css, js=js, debug=values.get('debug'), async=async, values=values)
|
||||
return [
|
||||
|
||||
@@ -1200,4 +1200,4 @@ actual arch.
|
||||
try:
|
||||
self.browse(vid)._check_xml()
|
||||
except Exception as e:
|
||||
self.raise_view_error("Can't validate view:\n%s" % (e.message or repr(e)), vid)
|
||||
self.raise_view_error("Can't validate view:\n%s" % e, vid)
|
||||
|
||||
@@ -42,6 +42,12 @@ class TestPyLint(TransactionCase):
|
||||
'parameter-unpacking',
|
||||
|
||||
'metaclass-assignment',
|
||||
|
||||
'exception-message-attribute',
|
||||
'indexing-exception',
|
||||
'old-raise-syntax',
|
||||
'raising-string',
|
||||
'unpacking-in-except',
|
||||
]
|
||||
|
||||
BAD_FUNCTIONS = [
|
||||
|
||||
@@ -92,8 +92,6 @@ def ustr(value, hint_encoding='utf-8', errors='strict'):
|
||||
|
||||
|
||||
def exception_to_unicode(e):
|
||||
if (sys.version_info[:2] < (2,6)) and hasattr(e, 'message'):
|
||||
return ustr(e.message)
|
||||
if hasattr(e, 'args'):
|
||||
return "\n".join((ustr(a) for a in e.args))
|
||||
try:
|
||||
|
||||
@@ -550,7 +550,7 @@ class PreforkServer(CommonServer):
|
||||
if e.errno not in [errno.EAGAIN]:
|
||||
raise
|
||||
except select.error as e:
|
||||
if e[0] not in [errno.EINTR]:
|
||||
if e.args[0] not in [errno.EINTR]:
|
||||
raise
|
||||
|
||||
def start(self):
|
||||
@@ -660,7 +660,7 @@ class Worker(object):
|
||||
try:
|
||||
select.select([self.multi.socket], [], [], self.multi.beat)
|
||||
except select.error as e:
|
||||
if e[0] not in [errno.EINTR]:
|
||||
if e.args[0] not in [errno.EINTR]:
|
||||
raise
|
||||
|
||||
def process_limit(self):
|
||||
|
||||
@@ -85,17 +85,12 @@ def xmlrpc_handle_exception_int(e):
|
||||
fault = xmlrpclib.Fault(RPC_FAULT_CODE_APPLICATION_ERROR, formatted_info)
|
||||
response = xmlrpclib.dumps(fault, allow_none=False, encoding=None)
|
||||
else:
|
||||
if hasattr(e, 'message') and e.message == 'AccessDenied': # legacy
|
||||
fault = xmlrpclib.Fault(RPC_FAULT_CODE_ACCESS_DENIED, str(e))
|
||||
response = xmlrpclib.dumps(fault, allow_none=False, encoding=None)
|
||||
#InternalError
|
||||
else:
|
||||
info = sys.exc_info()
|
||||
# Which one is the best ?
|
||||
formatted_info = "".join(traceback.format_exception(*info))
|
||||
#formatted_info = odoo.tools.exception_to_unicode(e) + '\n' + info
|
||||
fault = xmlrpclib.Fault(RPC_FAULT_CODE_APPLICATION_ERROR, formatted_info)
|
||||
response = xmlrpclib.dumps(fault, allow_none=None, encoding=None)
|
||||
info = sys.exc_info()
|
||||
# Which one is the best ?
|
||||
formatted_info = "".join(traceback.format_exception(*info))
|
||||
#formatted_info = odoo.tools.exception_to_unicode(e) + '\n' + info
|
||||
fault = xmlrpclib.Fault(RPC_FAULT_CODE_APPLICATION_ERROR, formatted_info)
|
||||
response = xmlrpclib.dumps(fault, allow_none=None, encoding=None)
|
||||
return response
|
||||
|
||||
def xmlrpc_handle_exception_string(e):
|
||||
@@ -116,7 +111,7 @@ def xmlrpc_handle_exception_string(e):
|
||||
elif isinstance(e, odoo.exceptions.DeferredException):
|
||||
info = e.traceback
|
||||
formatted_info = "".join(traceback.format_exception(*info))
|
||||
fault = xmlrpclib.Fault(odoo.tools.ustr(e.message), formatted_info)
|
||||
fault = xmlrpclib.Fault(odoo.tools.ustr(e), formatted_info)
|
||||
response = xmlrpclib.dumps(fault, allow_none=False, encoding=None)
|
||||
#InternalError
|
||||
else:
|
||||
|
||||
@@ -783,7 +783,11 @@ form: module.record_id""" % (xml_id,)
|
||||
except Exception as e:
|
||||
self.cr.rollback()
|
||||
exc_info = sys.exc_info()
|
||||
raise ParseError, (ustr(e), etree.tostring(rec).rstrip(), rec.getroottree().docinfo.URL, rec.sourceline), exc_info[2]
|
||||
pycompat.reraise(
|
||||
ParseError,
|
||||
ParseError(ustr(e), etree.tostring(rec).rstrip(), rec.getroottree().docinfo.URL, rec.sourceline),
|
||||
exc_info[2]
|
||||
)
|
||||
return True
|
||||
|
||||
def __init__(self, cr, module, idref, mode, report=None, noupdate=False, xml_filename=None):
|
||||
|
||||
@@ -20,6 +20,8 @@ if PY2:
|
||||
cls.next = cls.__next__
|
||||
del cls.__next__
|
||||
return cls
|
||||
|
||||
exec ('def reraise(tp, value, tb=None):\n raise tp, value, tb')
|
||||
else:
|
||||
# pylint: disable=bad-functions
|
||||
integer_types = (int,)
|
||||
@@ -34,3 +36,8 @@ else:
|
||||
|
||||
def implements_iterator(cls):
|
||||
return cls
|
||||
|
||||
def reraise(tp, value, tb=None):
|
||||
if value.__traceback__ != tb:
|
||||
raise value.with_traceback(tb)
|
||||
raise value
|
||||
|
||||
@@ -21,8 +21,10 @@ import functools
|
||||
from psycopg2 import OperationalError
|
||||
from types import CodeType
|
||||
import logging
|
||||
import sys
|
||||
import werkzeug
|
||||
|
||||
from . import pycompat
|
||||
from .misc import ustr
|
||||
|
||||
import odoo
|
||||
@@ -159,9 +161,8 @@ def test_expr(expr, allowed_codes, mode="eval"):
|
||||
except (SyntaxError, TypeError, ValueError):
|
||||
raise
|
||||
except Exception as e:
|
||||
import sys
|
||||
exc_info = sys.exc_info()
|
||||
raise ValueError, '"%s" while compiling\n%r' % (ustr(e), expr), exc_info[2]
|
||||
pycompat.reraise(ValueError, ValueError('"%s" while compiling\n%r' % (ustr(e), expr)), exc_info[2])
|
||||
assert_valid_codeobj(allowed_codes, code_obj, expr)
|
||||
return code_obj
|
||||
|
||||
@@ -320,9 +321,8 @@ def safe_eval(expr, globals_dict=None, locals_dict=None, mode="eval", nocopy=Fal
|
||||
except odoo.exceptions.MissingError:
|
||||
raise
|
||||
except Exception as e:
|
||||
import sys
|
||||
exc_info = sys.exc_info()
|
||||
raise ValueError, '%s: "%s" while evaluating\n%r' % (ustr(type(e)), ustr(e), expr), exc_info[2]
|
||||
pycompat.reraise(ValueError, ValueError('%s: "%s" while evaluating\n%r' % (ustr(type(e)), ustr(e), expr)), exc_info[2])
|
||||
def test_python_expr(expr, mode="eval"):
|
||||
try:
|
||||
test_expr(expr, _SAFE_OPCODES, mode=mode)
|
||||
|
||||
@@ -13,4 +13,4 @@ def check_with_xsd(tree_or_str, xsd_path):
|
||||
except etree.DocumentInvalid as xml_errors:
|
||||
#import UserError only here to avoid circular import statements with tools.func being imported in exceptions.py
|
||||
from odoo.exceptions import UserError
|
||||
raise UserError('\n'.join([e.message for e in xml_errors.error_log]))
|
||||
raise UserError('\n'.join(str(e) for e in xml_errors.error_log))
|
||||
|
||||
Reference in New Issue
Block a user