errorhandler

package
v1.48.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 8, 2026 License: GPL-2.0 Imports: 5 Imported by: 0

README

Error Handler Package

Глобальный обработчик ошибок с автоматическим логированием в файл и консоль.

Возможности

  • Централизованная обработка ошибок
  • Автоматическое логирование в файл и консоль
  • Обработка критических ошибок
  • Восстановление после panic с помощью recover
  • Защищённый запуск горутин
  • Разные уровни логирования: Debug, Info, Warn, Error, Critical

Инициализация

import "github.com/777genius/agent-notifications/internal/errorhandler"

// Инициализация при старте приложения
errorhandler.Init(
    true,  // logToConsole: выводить логи в консоль
    false, // exitOnCritical: завершать программу при критических ошибках
    true,  // recoveryEnabled: включить восстановление после panic
)

Использование

Обработка обычных ошибок
if err := someOperation(); err != nil {
    errorhandler.HandleError(err, "Failed to perform operation")
}
Обработка критических ошибок
if err := criticalOperation(); err != nil {
    errorhandler.HandleCriticalError(err, "Critical failure in operation")
    // Критические ошибки всегда выводятся в stderr
}
Защита от panic
func riskyFunction() {
    defer errorhandler.HandlePanic()

    // Ваш код, который может вызвать panic
    panic("something went wrong")
    // Panic будет перехвачен и залогирован
}
Обёртка функций с автоматическим recover
// Обычная функция
errorhandler.WithRecovery(func() {
    // Код, который может вызвать panic
})

// Функция с возвратом ошибки
err := errorhandler.WithRecoveryFunc(func() error {
    // Код, который может вызвать panic или вернуть ошибку
    return someOperation()
})
Безопасный запуск горутин
// Вместо обычного go func()
errorhandler.SafeGo(func() {
    // Код в горутине с защитой от panic
    riskyAsyncOperation()
})
Логирование
errorhandler.Debug("Debug message: %s", value)
errorhandler.Info("Info message: %s", value)
errorhandler.Warn("Warning: %s", warning)

Интеграция с logging

Пакет автоматически интегрируется с internal/logging и:

  • Логирует все ошибки в файл notification-debug.log
  • При включённом logToConsole выводит логи в stderr (для ошибок/предупреждений) или stdout (для info/debug)
  • Критические ошибки всегда выводятся в stderr, даже если logToConsole=false
  • Все выводы в консоль имеют префикс [claude-notifications] для удобной идентификации

Примеры из кода

main.go
func main() {
    errorhandler.Init(true, false, true)
    defer errorhandler.HandlePanic()

    // Основная логика
}
hooks.go
func (h *Handler) HandleHook(hookEvent string, input io.Reader) error {
    defer errorhandler.HandlePanic()

    // Обработка хука
}
Асинхронные операции
// notifier.go
errorhandler.SafeGo(func() {
    defer n.wg.Done()
    n.playSound(soundPath)
})

// webhook.go
errorhandler.SafeGo(func() {
    defer s.wg.Done()
    if err := s.Send(status, message, sessionID); err != nil {
        errorhandler.HandleError(err, "Async webhook send failed")
    }
})

Тестирование

go test ./internal/errorhandler/... -v

Примеры вывода

Вывод в консоль (stderr/stdout)

Все сообщения в консоль имеют префикс [claude-notifications]:

[claude-notifications] [2025-10-19 15:30:45] [ERROR] CRITICAL ERROR - Failed to initialize logger: permission denied
[claude-notifications] PANIC: unexpected nil pointer
[claude-notifications] [2025-10-19 15:30:46] [INFO] Notification sent successfully
[claude-notifications] [2025-10-19 15:30:47] [WARN] Rate limit approaching threshold
Вывод в файл (notification-debug.log)

Файловый лог не содержит префикс плагина:

[2025-10-19 15:30:45] [ERROR] CRITICAL ERROR - Failed to initialize logger: permission denied
[2025-10-19 15:30:45] [ERROR] PANIC RECOVERED: unexpected nil pointer
runtime/debug.Stack()...
[2025-10-19 15:30:46] [INFO] Notification sent successfully
[2025-10-19 15:30:47] [WARN] Rate limit approaching threshold

Documentation

Overview

Example

Example demonstrates the error handler usage with console output

package main

import (
	"errors"
	"fmt"

	"github.com/777genius/agent-notifications/internal/errorhandler"
	"github.com/777genius/agent-notifications/internal/logging"
)

func main() {
	// Initialize logger (in real usage this would be done in main.go)
	if _, err := logging.InitLogger("."); err != nil {
		fmt.Printf("Failed to initialize logger: %v\n", err)
		return
	}
	defer logging.Close()

	// Initialize error handler with console output enabled
	errorhandler.Init(true, false, true)

	// Example 1: Handle a normal error
	err := errors.New("connection timeout")
	errorhandler.HandleError(err, "Failed to connect to webhook")

	// Example 2: Log info message
	errorhandler.Info("Notification sent successfully")

	// Example 3: Log warning
	errorhandler.Warn("Rate limit at 80%% capacity")

	// Example 4: Protected function execution
	errorhandler.WithRecovery(func() {
		fmt.Println("Safe execution")
	})

	// Output will be in console with [claude-notifications] prefix:
	// [claude-notifications] [timestamp] [ERROR] Failed to connect to webhook: connection timeout
	// [claude-notifications] [timestamp] [INFO] Notification sent successfully
	// [claude-notifications] [timestamp] [WARN] Rate limit at 80% capacity
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Debug

func Debug(format string, args ...interface{})

Debug logs a debug message using the default handler

func HandleCriticalError

func HandleCriticalError(err error, context string)

HandleCriticalError handles a critical error using the default handler

func HandleError

func HandleError(err error, context string)

HandleError handles a general error using the default handler

func HandlePanic

func HandlePanic()

HandlePanic recovers from a panic using the default handler

func Info

func Info(format string, args ...interface{})

Info logs an info message using the default handler

func Reset

func Reset()

Reset resets the error handler (for testing only) WARNING: This is not thread-safe and should only be called in tests when no other goroutines are using the error handler

func SafeGo

func SafeGo(fn func())

SafeGo runs a goroutine with panic recovery

Example

ExampleSafeGo demonstrates safe goroutine execution

package main

import (
	"fmt"

	"github.com/777genius/agent-notifications/internal/errorhandler"
)

func main() {
	errorhandler.Init(true, false, true)

	done := make(chan bool)

	// This goroutine is protected from panics
	errorhandler.SafeGo(func() {
		defer func() { done <- true }()
		fmt.Println("Running in safe goroutine")
	})

	<-done
}

func Warn

func Warn(format string, args ...interface{})

Warn logs a warning using the default handler

func WithRecovery

func WithRecovery(fn func())

WithRecovery wraps a function with panic recovery

func WithRecoveryFunc

func WithRecoveryFunc(fn func() error) error

WithRecoveryFunc wraps a function that returns an error with panic recovery

Types

type ErrorHandler

type ErrorHandler struct {
	// contains filtered or unexported fields
}

ErrorHandler provides global error handling and logging

func GetHandler

func GetHandler() *ErrorHandler

GetHandler returns the default error handler (auto-initializes with defaults if needed)

func Init

func Init(logToConsole, exitOnCritical, recoveryEnabled bool) *ErrorHandler

Init initializes the global error handler with custom settings If handler is already initialized, returns the existing handler

func (*ErrorHandler) Debug

func (h *ErrorHandler) Debug(format string, args ...interface{})

Debug logs a debug message

func (*ErrorHandler) HandleCriticalError

func (h *ErrorHandler) HandleCriticalError(err error, context string)

HandleCriticalError handles a critical error that may require program termination

func (*ErrorHandler) HandleError

func (h *ErrorHandler) HandleError(err error, context string)

HandleError handles a general error

func (*ErrorHandler) HandlePanic

func (h *ErrorHandler) HandlePanic()

HandlePanic recovers from a panic and logs it

func (*ErrorHandler) Info

func (h *ErrorHandler) Info(format string, args ...interface{})

Info logs an informational message

func (*ErrorHandler) Warn

func (h *ErrorHandler) Warn(format string, args ...interface{})

Warn logs a warning message

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL