saferun.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. "runtime/debug"
  19. "github.com/lf-edge/ekuiper/internal/conf"
  20. "github.com/lf-edge/ekuiper/pkg/api"
  21. )
  22. // SafeRun will catch and return the panic error together with other errors
  23. // When running in a rule, the whole rule must be in this mode
  24. // The sub processes or go routines under a rule should also use this mode
  25. // To make sure all rule panic won't affect the whole system
  26. // Also consider running in this mode if the function should not affect the whole system
  27. func SafeRun(fn func() error) (err error) {
  28. defer func() {
  29. if r := recover(); r != nil {
  30. debug.PrintStack()
  31. switch x := r.(type) {
  32. case string:
  33. err = errors.New(x)
  34. case error:
  35. err = x
  36. default:
  37. err = fmt.Errorf("%#v", x)
  38. }
  39. }
  40. }()
  41. err = fn()
  42. return err
  43. }
  44. // DrainError a non-block function to send out the error to the error channel
  45. // Only the first error will be sent out and received then the rule will be terminated
  46. // Thus the latter error will just skip
  47. // It is usually the error outlet of a op/rule.
  48. func DrainError(ctx api.StreamContext, err error, errCh chan<- error) {
  49. if ctx != nil {
  50. ctx.GetLogger().Errorf("runtime error: %v", err)
  51. } else {
  52. conf.Log.Errorf("runtime error: %v", err)
  53. }
  54. select {
  55. case errCh <- err:
  56. default:
  57. }
  58. }