DEV Community

Khaled Said
Khaled Said

Posted on

1

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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay