DEV Community

Khaled Said
Khaled Said

Posted on

Adjust Odoo Error Codes with monkey patching

In API integration scenario, Odoo error codes may not be satisfactory. In Odoo the default error code of json request is 200. you could handle such case by overriding _handle_exception method found in the following path: https://github.com/odoo/odoo/blob/9d6095da7b2508193ce42cc951ffdd2d3adf5856/odoo/http.py#L649

an example of such code would be as following:

import logging
import werkzeug

import odoo
from odoo.http import AuthenticationError, JsonRequest, serialize_exception, SessionExpiredException

_logger = logging.getLogger(__name__)


def _handle_exception(self, exception):
    """Called within an except block to allow converting exceptions
       to arbitrary responses. Anything returned (except None) will
       be used as response."""
    try:
        return super(JsonRequest, self)._handle_exception(exception)
    except Exception:
        if not isinstance(exception, SessionExpiredException):
            if exception.args and exception.args[0] == "bus.Bus not available in test mode":
                _logger.info(exception)
            elif isinstance(exception, (odoo.exceptions.UserError,
                                        werkzeug.exceptions.NotFound)):
                _logger.warning(exception)
            else:
                _logger.exception("Exception during JSON request handling.")
        error = {
            'code': 400,
            'message': "Odoo Server Error",
            'data': serialize_exception(exception),
        }
        if isinstance(exception, werkzeug.exceptions.NotFound):
            error['http_status'] = 404
            error['code'] = 404
            error['message'] = "404: Not Found"
        if isinstance(exception, AuthenticationError):
            error['code'] = 100
            error['message'] = "Odoo Session Invalid"
        if isinstance(exception, SessionExpiredException):
            error['code'] = 100
            error['message'] = "Odoo Session Expired"
        if isinstance(exception, werkzeug.exceptions.UnprocessableEntity):
            error['code'] = 422
            error['message'] = "422 Unprocessable Entity"
        return self._json_response(error=error)


JsonRequest._handle_exception = _handle_exception

Enter fullscreen mode Exit fullscreen mode

you could see in line 40 that you could add a new error code which is in Odoo before. also note line 46 which apply the monkey patching. so you have to make sure that your module is loaded before any module overriding such method by adjusting module dependency.

Top comments (0)