saferun.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright 2022 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package infra
  15. import (
  16. "errors"
  17. "fmt"
  18. "github.com/lf-edge/ekuiper/pkg/api"
  19. "runtime/debug"
  20. )
  21. // SafeRun will catch and return the panic error together with other errors
  22. // When running in a rule, the whole rule must be in this mode
  23. // The sub processes or go routines under a rule should also use this mode
  24. // To make sure all rule panic won't affect the whole system
  25. // Also consider running in this mode if the function should not affect the whole system
  26. func SafeRun(fn func() error) (err error) {
  27. defer func() {
  28. if r := recover(); r != nil {
  29. debug.PrintStack()
  30. switch x := r.(type) {
  31. case string:
  32. err = errors.New(x)
  33. case error:
  34. err = x
  35. default:
  36. err = fmt.Errorf("%#v", x)
  37. }
  38. }
  39. }()
  40. err = fn()
  41. return err
  42. }
  43. // DrainError a non-block function to send out the error to the error channel
  44. // Only the first error will be sent out and received then the rule will be terminated
  45. // Thus the latter error will just skip
  46. // It is usually the error outlet of a op/rule.
  47. func DrainError(ctx api.StreamContext, err error, errCh chan<- error) {
  48. ctx.GetLogger().Errorf("runtime error: %v", err)
  49. select {
  50. case errCh <- err:
  51. default:
  52. }
  53. }