Skip to content

Commit

Permalink
fixup! fixup! sf_base: add decorator to gracefully handle exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
TDu committed Oct 30, 2023
1 parent 96812b3 commit 041e7e5
Showing 1 changed file with 7 additions and 4 deletions.
11 changes: 7 additions & 4 deletions shopfloor_base/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import os
from functools import wraps

from odoo.exceptions import ValidationError
from odoo.exceptions import UserError, ValidationError
from odoo.modules.module import load_information_from_description_file
from odoo.tools.config import config as odoo_config

Expand Down Expand Up @@ -34,24 +34,27 @@ def wrapped(*args, **kwargs):
return _ensure_model


def catch_errors(response_error):
def catch_errors(response_error, exceptions_to_catch=None):
"""Decorator for service endpoints to gracefully handle some exceptions.
The decorator is passed a function with the same arguments than the function
handlling the endpoint, plus a keyword argument called `message`.
"""

if exceptions_to_catch is None:
exceptions_to_catch = (ValidationError, UserError)

def _catch_errors(fn):
@wraps(fn)
def wrapper(self, *args, **kwargs):
savepoint = self._actions_for("savepoint").new()
try:
res = fn(self, *args, **kwargs)
except ValidationError as ex:
except exceptions_to_catch as ex:
savepoint.rollback()
message = {
"message_type": "error",
"body": ex.name,
"body": str(ex),
}
return response_error(self, *args, **kwargs, message=message)
savepoint.release()
Expand Down

0 comments on commit 041e7e5

Please sign in to comment.