saferun.go 1.7 KB

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