4 examples of 'golang try catch' in Go

Every line of 'golang try catch' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Go code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
68func try(fun func(), handler func(interface{})) {
69 defer func() {
70 if err := recover(); err != nil {
71 handler(err)
72 }
73 }()
74 fun()
75}
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

37func Try(fn func() Result, failure ...Result) Result {
38 var failed bool
39 var actionResponse Result
40
41 func() {
42 defer func() {
43 if rec := recover(); rec != nil {
44 failed = true
45 }
46 }()
47 actionResponse = fn()
48 }()
49
50 if failed {
51 if len(failure) > 0 {
52 return failure[0]
53 }
54 return defaultFailureResponse
55 }
56
57 return actionResponse
58}
66func (v *namespace) Catch(f HandlerFunc) Namespace {
67 v.catch = f
68 return v
69}
71func Catch(fns ...func(error)) {
72 if r := recover(); r != nil && len(fns) > 0 {
73 if err, match := r.(error); match {
74 for _, fn := range fns {
75 fn(err)
76 }
77 } else {
78 err := fmt.Errorf("%v", r)
79 for _, fn := range fns {
80 fn(err)
81 }
82 }
83 }
84}

Related snippets