Enable Dark Mode!
how-to-run-efficient-error-management-with-the-odoo-14-exceptions.jpg
By: Sarath S

How to Run Efficient Error Management With the Odoo 14 Exceptions

In this blog, we are going to discuss how error management will be effectively done in Odoo 14. By the end of the blog, you will understand a few core exception types that the Odoo exception module defines. 

The exceptions provided for error management by Odoo are as follows: -

1) AccessDenied

2) AccessError

3) CacheMiss

4) MissingError

5) RedirectWarning

6) UserError

7) ValidationError

Since these are the Odoo exceptions, it can be executed as ‘odoo.exceptions.AccessDenied()’. We can move through each exception listed above in detail and understand the working of each exception with an example condition and error managed in Odoo 14.

1) odoo.exceptions.AccessDenied()

This exception gets executed when the user tries to login or signup with wrong passwords or with any invalid parameters. Let us look at an example, first of all, we need to import the AccessDenied exception from odoo.exceptions are as follows:

from odoo.exceptions import AccessDenied
@http.route('/web/login', type='http', auth="none")
def web_login(self, redirect=None, **kw):
             if request.httprequest.method == 'POST':
   old_uid = request.uid
   try:
       uid = request.session.authenticate(request.session.db, request.params['login'], request.params['password'])
       request.params['login_success'] = True
       return http.redirect_with_hash(self._login_redirect(uid, redirect=redirect))
   except odoo.exceptions.AccessDenied as e:
       request.uid = old_uid
       if e.args == odoo.exceptions.AccessDenied().args:
           values['error'] = _("The login details is not correct")

Here we have given a condition that if the login details provided are correct then the page redirects to the corresponding page and else it raises an exception of AccessDenied as described here.

except odoo.exceptions.AccessDenied as e:
       request.uid = old_uid
       if e.args == odoo.exceptions.AccessDenied().args:
           values['error'] = _("The login details is not correct")

This is the syntax for the AccessDenied exception:

“odoo.exceptions.AccessDenied(message='Access Denied')”.

The following image depicts the AccessDenied exception in operation:

how-to-run-efficient-error-management-with-the-odoo-14-exceptions

2) odoo.exceptions.AccessError(message)

The odoo.exceptions.AccessError() is defined based on the error occurring due to access rights. Let us look at an example, of the AccessError exception as follows:

from odoo import api, fields, models, _
from odoo.exceptions import AccessError
class Partner(models.Model):
   _inherit = "res.partner"
 @api.model
   def create(self, vals):
       user_id = self.env.user
       users_with_groups = user_id.filtered(lambda user:
           user.has_group('sales_team.group_sale_manager')
        )
       if not users_with_groups:
           raise AccessError(_("You are not allowed to          createCustomer/Vendor. Please contact to your Manager."))
return super(Partner, self).create(vals)

We have inherited the res.partner model and on the creation of the partner, it checks whether the logged-in user belongs to the group of Sales managers. If not it raises an exception of AccessError as follows.

if not users_with_groups:
           raise AccessError(_("You are not allowed to          createCustomer/Vendor. Please contact to your Manager."))

The following image depicts the AccessError exception in operation:

how-to-run-efficient-error-management-with-the-odoo-14-exceptions

3) odoo.exceptions.CacheMiss(record, field)

           This exception is used when the record field is missing from the cache, so we can use the CacheMiss() exception. And the format of this exception is as follows; odoo.exceptions.CacheMiss(record, field).

def get(self, record, field):
           raise CacheMiss(record, field)

As defined in the above code we can raise the CacheMiss exception in Odoo.

4) odoo.exceptions.MissingError(message)

          The MissingError() exception is used to inform the user that the record we are updating or searching is being deleted. Mainly informs about Missing records, here is an example of how it works:

from odoo.exceptions import MissingError, RedirectWarning, CacheMiss
class AccountMove(models.Model):
   _inherit = "account.move"
   @api.onchange('partner_id')
   def _onchange_partner_id(self):
       if not self.partner_id.phone:
           raise MissingError(_("This customer does not exist."))

Here if the selected partner_id which does not contain the phone number in the phone field, it raises the MissingError exception as follows.

if not self.partner_id.phone:
           raise MissingError(_("This customer does not exist."))

The following image depicts the MissingError exception in operation:

how-to-run-efficient-error-management-with-the-odoo-14-exceptions

5) odoo.exceptions.RedirectWarning(message,action,button_text,additional_context=None)

The exception RedirectWarning() can be used for the user to redirect the page to the specific instead of just showing the warning message. In this exception, the important parameters required are odoo.exceptions.RedirectWarning(message,action,button_text,additional_context=None).We can look at a simple example to make the operation more clearer:

from odoo import api, fields, models, _
from odoo.exceptions import RedirectWarning
class AccountMove(models.Model):
   _inherit = "account.move"
   @api.onchange('partner_id')
   def _onchange_partner_id(self):
           rec_account = self.partner_id.property_account_receivable_id
           pay_account = self.partner_id.property_account_payable_id
           if not rec_account and not pay_account:
               action = self.env.ref('account.action_account_config')
               msg = _(
                   'Cannot find a account details for this customer \nPlease go to Account Configuration and install chart of accounts')
               raise RedirectWarning(msg, action.id, _('Go to the configuration panel'))

As we can see here, by using this exception, we are able to redirect to a specific page. Moreover, here we have defined the parameters:

action = self.env.ref('account.action_account_config')
msg = _(
                   'Cannot find a account details for this customer \nPlease go to Account Configuration and install chart of accounts')

The defined action is of the account configuration menu and the message to specify is also defined. The RedirectWarning exception is raised as below:

raise RedirectWarning(msg, action.id, _('Go to the configuration panel'))

Therefore when we click on the button, the page redirects to the configuration menu action, that is to the settings page of the account.

The following image depicts the RedirectWarning exception in operation:

how-to-run-efficient-error-management-with-the-odoo-14-exceptions

6) odoo.exceptions.UserError(message)

The UserError exception is executed when any action or anything in Odoo undergoes against the logic and is managed by the client. The following example depicts its operation of it;

from odoo import fields, models, api,_
from odoo.exceptions import UserError
class ResCompany(models.Model):
   _inherit = 'res.company'
   @api.onchange('vat')
   def _onchange_vat(self):
       if len(self.vat) < 15:
           raise UserError(_('VAT REGISTER NUMBER SHOULD CONTAIN 15 DIGITS'))

When the vat number provided by the user is less than 15 digits, the UserError exception raises as depicted in the following screenshot;

how-to-run-efficient-error-management-with-the-odoo-14-exceptions

7) odoo.exceptions.ValidationError(message)

ValidationError exception is raised when the python constraints get violated or fail. For example, when a user has the same mobile number or email address of the other user, exception ValidationError can be used. Let's move into an example to get a clearer perspective;

from odoo.exceptions import  ValidationError
class Partner(models.Model):
   _inherit = "res.partner"
 @api.model
 def create(self, vals):
       if self.env["res.partner"].search([("mobile", "=", self.mobile)]):
           raise ValidationError(_("Another user is already created using this mobile number"))
       return super(Partner, self).create(vals)

The ValidationError is raised when the partner is created with the same mobile number that already exists.

raise ValidationError(_("Another user is already created using this mobile number"))

And the message is also specified in the exception raised as described by you in the above code is the same as the one depicted in the following screenshot of the exception in operation;

how-to-run-efficient-error-management-with-the-odoo-14-exceptions

In conclusion, these are the error handling management exception tools used in Odoo14 for better performance and execution and further effective operations of the aspects with Odoo. Moreover, these exceptions will ensure that all the operations of the users and their aligned operations are based on the aspects defined by you.


Odoo Training Package
Odoo Implementation Package

If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment

 
whatsapp
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, Kinfra Techno Park
Kakkancherry, Calicut
Kerala, India - 673635

location

London

Cybrosys Limited
Alpha House,
100 Borough High Street, London,
SE1 1LB, United Kingdom

location

Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.

location

Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message