Skip to content

09 exceptions

Zuko edited this page Jan 21, 2026 · 1 revision

Exception Handling

Custom exception types và global exception handler

Overview

Core cung cấp:

  • Custom exception types
  • Global exception handler
  • Handler registration
  • Auto message box display

Exception Types

AppException

Base exception cho application:

from core import AppException

raise AppException('Error message', title='Custom Title')

ConfigError

Configuration errors:

from core import ConfigError

raise ConfigError('Invalid config value')

ServiceError

Service-related errors:

from core import ServiceError

raise ServiceError('Service initialization failed')

UIError

UI-related errors:

from core import UIError

raise UIError('Widget not found')

ExceptionHandler

Global Handler

from core import ExceptionHandler

# Setup (auto-called by QtAppContext)
ExceptionHandler.setupGlobalHandler()

Custom Handlers

handler = ExceptionHandler()

def customHandler(e: MyException):
    # Handle exception
    return True  # Handled

handler.registerHandler(MyException, customHandler)

Usage Examples

Raising Exceptions

from core import AppException, ConfigError

# Application exception
if not valid:
    raise AppException('Validation failed', title='Validation Error')

# Config exception
if not config_file_exists:
    raise ConfigError('Config file not found')

Exception Logging

from core.Logging import logger

try:
    risky_operation()
except Exception as e:
    logger.opt(exception=e).error('Operation failed')
    raise

Best Practices

✅ DO

# Use specific exception types
raise ConfigError('Invalid value')

# Log exceptions
try:
    # Code...
    pass
except Exception as e:
    logger.opt(exception=e).error('Failed')
    raise

# Provide context
raise AppException(f'Failed to load user {userId}', title='Load Error')

❌ DON'T

# Don't catch silently
try:
    # Code...
    pass
except:
    pass  # Wrong!

# Don't use generic Exception
raise Exception('Error')  # Use AppException instead

Related Documentation

Clone this wiki locally