1
0

err.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Package common provides common utility functions for error handling, formatting, and multi-error management.
  2. package common
  3. import (
  4. "errors"
  5. "fmt"
  6. "runtime/debug"
  7. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  8. )
  9. // NewErrorf creates a new error with formatted message.
  10. func NewErrorf(format string, a ...any) error {
  11. msg := fmt.Sprintf(format, a...)
  12. return errors.New(msg)
  13. }
  14. // NewError creates a new error from the given arguments.
  15. func NewError(a ...any) error {
  16. msg := fmt.Sprintln(a...)
  17. return errors.New(msg)
  18. }
  19. // Recover handles panic recovery and logs the panic error if a message is provided.
  20. func Recover(msg string) any {
  21. panicErr := recover()
  22. if panicErr != nil {
  23. if msg != "" {
  24. logger.Error(msg, "panic:", panicErr)
  25. }
  26. }
  27. return panicErr
  28. }
  29. // GoRecover runs fn in a new goroutine guarded by a recover, so a panic in a
  30. // background goroutine is logged (with name and a stack trace) instead of taking
  31. // the whole process down. name identifies the goroutine in the log.
  32. func GoRecover(name string, fn func()) {
  33. go func() {
  34. defer func() {
  35. if r := recover(); r != nil {
  36. logger.Error("panic in goroutine", name, ":", r, "\n"+string(debug.Stack()))
  37. }
  38. }()
  39. fn()
  40. }()
  41. }