Ir al contenido
Odoo Menú
  • Identificarse
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • TPV para tiendas
    • TPV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en directo
    • e-learning
    Cadena de suministro
    • Inventario
    • Fabricación
    • PLM
    • Compra
    • Mantenimiento
    • Calidad
    Recursos Humanos
    • Empleados
    • Reclutamiento
    • Ausencias
    • Evaluación
    • Referencias
    • Flota
    Marketing
    • Marketing social
    • Marketing por correo electrónico
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyecto
    • Partes de horas
    • Servicio de campo
    • Servicio de asistencia
    • Planificación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Conocimientos
    • WhatsApp
    Aplicaciones de terceros Studio de Odoo Plataforma de Odoo Cloud
  • Industrias
    Comercio al por menor
    • Librería
    • Tienda de ropa
    • Tienda de muebles
    • Tienda de ultramarinos
    • Ferretería
    • Juguetería
    Alimentación y hostelería
    • Bar y pub
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidor de bebidas
    • Hotel
    Inmueble
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión inmobiliaria
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Empresa contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Fabricación
    • Textil
    • Metal
    • Muebles
    • Alimentos
    • Cervecería
    • Regalos de empresas
    Salud y bienestar
    • Club deportivo
    • Óptica
    • Gimnasio
    • Terapeutas
    • Farmacia
    • Peluquería
    Oficios
    • Handyman
    • Hardware y soporte técnico
    • Sistemas de energía solar
    • Zapatero
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin ánimo de lucro
    • Agencia de protección del medio ambiente
    • Alquiler de paneles publicitarios
    • Estudio fotográfico
    • Alquiler de bicicletas
    • Distribuidor de software
    Explorar todos los sectores
  • Comunidad
    Aprender
    • Tutoriales
    • Documentación
    • Certificaciones
    • Formación
    • Blog
    • Podcast
    Potenciar la educación
    • Programa de formación
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtener el software
    • Descargar
    • Comparar ediciones
    • Versiones
    Colaborar
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Convertirse en partner
    • Servicios para partners
    • Registrar tu empresa contable
    Obtener servicios
    • Encontrar un partner
    • Encontrar un asesor fiscal
    • Contacta con un experto
    • Servicios de implementación
    • Referencias de clientes
    • Ayuda
    • Actualizaciones
    GitHub YouTube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicitar una demostración
  • Precios
  • Ayuda

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

  • CRM
  • e-Commerce
  • Contabilidad
  • Inventario
  • PoS
  • Proyecto
  • MRP
All apps
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Ayuda

[11.0] How to inherit _handle_exception method in http file

Suscribirse

Reciba una notificación cuando haya actividad en esta publicación

Se marcó esta pregunta
httprequestodoo11JsonRequest
1 Responder
6162 Vistas
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
Descartar
Avatar
Ian Muir
Mejor respuesta

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
Descartar
¿Le interesa esta conversación? ¡Participe en ella!

Cree una cuenta para poder utilizar funciones exclusivas e interactuar con la comunidad.

Inscribirse
Publicaciones relacionadas Respuestas Vistas Actividad
How to call a function from JS file
rpc httprequest JsonRequest
Avatar
Avatar
1
ago 20
8246
How can I handle arbitrary incoming `application/json` HTTP requests in Odoo?
httprequest http.py http.route JsonRequest
Avatar
1
nov 21
4352
create backorder odoo after validate purchase shipment ? Resuelto
odoo11
Avatar
Avatar
1
oct 25
12068
I can't create any sub-task
odoo11
Avatar
Avatar
Avatar
2
jul 24
3682
odoo 11 display calendar widget in website layout
odoo11
Avatar
Avatar
1
jun 24
5986
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento Odoo.sh
  • Ayuda
  • Actualizar
  • Desarrollos personalizados
  • Educación
  • Encontrar un asesor fiscal
  • Encontrar un partner
  • Convertirse en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contacta con nosotros
  • Puestos de trabajo
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Información legal • Privacidad
  • Seguridad
الْعَرَبيّة 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 es un conjunto de aplicaciones de código abierto que cubren todas las necesidades de tu empresa: CRM, comercio electrónico, contabilidad, inventario, punto de venta, gestión de proyectos, etc.

La propuesta única de valor de Odoo es ser muy fácil de usar y totalmente integrado.

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