Skip to Content
Odoo Menu
  • Sign in
  • Try it free
  • Apps
    Finance
    • Accounting
    • Invoicing
    • Expenses
    • Spreadsheet (BI)
    • Documents
    • Sign
    Sales
    • CRM
    • Sales
    • POS Shop
    • POS Restaurant
    • Subscriptions
    • Rental
    Websites
    • Website Builder
    • eCommerce
    • Blog
    • Forum
    • Live Chat
    • eLearning
    Supply Chain
    • Inventory
    • Manufacturing
    • PLM
    • Purchase
    • Maintenance
    • Quality
    Human Resources
    • Employees
    • Recruitment
    • Time Off
    • Appraisals
    • Referrals
    • Fleet
    Marketing
    • Social Marketing
    • Email Marketing
    • SMS Marketing
    • Events
    • Marketing Automation
    • Surveys
    Services
    • Project
    • Timesheets
    • Field Service
    • Helpdesk
    • Planning
    • Appointments
    Productivity
    • Discuss
    • Approvals
    • IoT
    • VoIP
    • Knowledge
    • WhatsApp
    Third party apps Odoo Studio Odoo Cloud Platform
  • Industries
    Retail
    • Book Store
    • Clothing Store
    • Furniture Store
    • Grocery Store
    • Hardware Store
    • Toy Store
    Food & Hospitality
    • Bar and Pub
    • Restaurant
    • Fast Food
    • Guest House
    • Beverage Distributor
    • Hotel
    Real Estate
    • Real Estate Agency
    • Architecture Firm
    • Construction
    • Estate Management
    • Gardening
    • Property Owner Association
    Consulting
    • Accounting Firm
    • Odoo Partner
    • Marketing Agency
    • Law firm
    • Talent Acquisition
    • Audit & Certification
    Manufacturing
    • Textile
    • Metal
    • Furnitures
    • Food
    • Brewery
    • Corporate Gifts
    Health & Fitness
    • Sports Club
    • Eyewear Store
    • Fitness Center
    • Wellness Practitioners
    • Pharmacy
    • Hair Salon
    Trades
    • Handyman
    • IT Hardware & Support
    • Solar Energy Systems
    • Shoe Maker
    • Cleaning Services
    • HVAC Services
    Others
    • Nonprofit Organization
    • Environmental Agency
    • Billboard Rental
    • Photography
    • Bike Leasing
    • Software Reseller
    Browse all Industries
  • Community
    Learn
    • Tutorials
    • Documentation
    • Certifications
    • Training
    • Blog
    • Podcast
    Empower Education
    • Education Program
    • Scale Up! Business Game
    • Visit Odoo
    Get the Software
    • Download
    • Compare Editions
    • Releases
    Collaborate
    • Github
    • Forum
    • Events
    • Translations
    • Become a Partner
    • Services for Partners
    • Register your Accounting Firm
    Get Services
    • Find a Partner
    • Find an Accountant
    • Meet an advisor
    • Implementation Services
    • Customer References
    • Support
    • Upgrades
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Get a demo
  • Pricing
  • Help

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Accounting
  • Inventory
  • PoS
  • Project
  • MRP
All apps
You need to be registered to interact with the community.
All Posts People Badges
Tags (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Tags (View all)
odoo accounting v14 pos v15
About this forum
Help

[11.0] How to inherit _handle_exception method in http file

Subscribe

Get notified when there's activity on this post

This question has been flagged
httprequestodoo11JsonRequest
1 Reply
6037 Views
Avatar
Gokulakrishnan Murugesan

Hi All,


I want to inherit the _handle_exception method from http.py file and want to rename Odoo Server Error to Custom Server Error.

class JsonRequest(WebRequest):
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, (odoo.exceptions.Warning, SessionExpiredException,
odoo.exceptions.except_orm, werkzeug.exceptions.NotFound)):
_logger.exception("Exception during JSON request handling.")
error = {
'code': 200,
'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"
return self._json_response(error=error)
In the above method, i want to replace the naem from doo to custom name.

Thanks in advance.
1
Avatar
Discard
Avatar
Ian Muir
Best Answer

Hi Gokulakrishnan

I came across your question, in searching for the exact thing myself for over a year like yourself.  However, as God would have it, I found the solution and I'll post it below for you and anyone else who may be interested:

Create a new controller file and don't forget to place it in the __init__.py file in the controllers directory.  You could always place it in an existing controller file, but a separate file is cleaner imho.

your_controller_file.py

# -*- coding: utf-8 -*-

import werkzeug
import logging
import odoo
import odoo.exceptions
import werkzeug.exceptions
import traceback
from odoo.http import JsonRequest, AuthenticationError, SessionExpiredException, ustr
_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, (odoo.exceptions.Warning, SessionExpiredException,
odoo.exceptions.except_orm, werkzeug.exceptions.NotFound)):
_logger.exception("Exception during JSON request handling.")
error = {
'code': 200,
'message': "Custom Name 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'] = "Custom Name Session Invalid"
if isinstance(exception, SessionExpiredException):
error['code'] = 100
error['message'] = "Custom Name Session Expired"
return self._json_response(error=error)

setattr(JsonRequest, '_handle_exception', _handle_exception)

def serialize_exception(e):
tmp = {
"name": type(e).__module__ + "." + type(e).__name__ if type(e).__module__ else type(e).__name__,
"debug": traceback.format_exc(),
"message": ustr(e),
"arguments": e.args,
"exception_type": "internal_error"
}
if isinstance(e, odoo.exceptions.UserError):
tmp["exception_type"] = "user_error"
elif isinstance(e, odoo.exceptions.Warning):
tmp["exception_type"] = "warning"
elif isinstance(e, odoo.exceptions.RedirectWarning):
tmp["exception_type"] = "warning"
elif isinstance(e, odoo.exceptions.AccessError):
tmp["exception_type"] = "access_error"
elif isinstance(e, odoo.exceptions.MissingError):
tmp["exception_type"] = "missing_error"
elif isinstance(e, odoo.exceptions.AccessDenied):
tmp["exception_type"] = "access_denied"
elif isinstance(e, odoo.exceptions.ValidationError):
tmp["exception_type"] = "validation_error"
elif isinstance(e, odoo.exceptions.except_orm):
tmp["exception_type"] = "except_orm"
return tmp

Adjust the above parts where it says "Custom Name" to your liking, save, restart the service/server and you're good to go.

The "setattr(JsonRequest, '_handle_exception', _handle_exception)" line above, is the key line, as this is where the override takes place.  Answer inspired from https://stackoverflow.com/questions/62388254/in-odoos-controller-file-how-to-change-the-json-response-format-when-the-type

1
Avatar
Discard
Enjoying the discussion? Don't just read, join in!

Create an account today to enjoy exclusive features and engage with our awesome community!

Sign up
Related Posts Replies Views Activity
How to call a function from JS file
rpc httprequest JsonRequest
Avatar
Avatar
1
Aug 20
8158
How can I handle arbitrary incoming `application/json` HTTP requests in Odoo?
httprequest http.py http.route JsonRequest
Avatar
1
Nov 21
4218
create backorder odoo after validate purchase shipment ? Solved
odoo11
Avatar
Avatar
1
Oct 25
11882
I can't create any sub-task
odoo11
Avatar
Avatar
Avatar
2
Jul 24
3577
odoo 11 display calendar widget in website layout
odoo11
Avatar
Avatar
1
Jun 24
5884
Community
  • Tutorials
  • Documentation
  • Forum
Open Source
  • Download
  • Github
  • Runbot
  • Translations
Services
  • Odoo.sh Hosting
  • Support
  • Upgrade
  • Custom Developments
  • Education
  • Find an Accountant
  • Find a Partner
  • Become a Partner
About us
  • Our company
  • Brand Assets
  • Contact us
  • Jobs
  • Events
  • Podcast
  • Blog
  • Customers
  • Legal • Privacy
  • Security
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo is a suite of open source business apps that cover all your company needs: CRM, eCommerce, accounting, inventory, point of sale, project management, etc.

Odoo's unique value proposition is to be at the same time very easy to use and fully integrated.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now