github.com/gogf/gf/v2@v2.7.4/util/gutil/gutil_try_catch.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/gogf/gf. 6 7 package gutil 8 9 import ( 10 "context" 11 12 "github.com/gogf/gf/v2/errors/gcode" 13 "github.com/gogf/gf/v2/errors/gerror" 14 ) 15 16 // Throw throws out an exception, which can be caught be TryCatch or recover. 17 func Throw(exception interface{}) { 18 panic(exception) 19 } 20 21 // Try implements try... logistics using internal panic...recover. 22 // It returns error if any exception occurs, or else it returns nil. 23 func Try(ctx context.Context, try func(ctx context.Context)) (err error) { 24 if try == nil { 25 return 26 } 27 defer func() { 28 if exception := recover(); exception != nil { 29 if v, ok := exception.(error); ok && gerror.HasStack(v) { 30 err = v 31 } else { 32 err = gerror.NewCodef(gcode.CodeInternalPanic, "%+v", exception) 33 } 34 } 35 }() 36 try(ctx) 37 return 38 } 39 40 // TryCatch implements `try...catch..`. logistics using internal `panic...recover`. 41 // It automatically calls function `catch` if any exception occurs and passes the exception as an error. 42 // If `catch` is given nil, it ignores the panic from `try` and no panic will throw to parent goroutine. 43 // 44 // But, note that, if function `catch` also throws panic, the current goroutine will panic. 45 func TryCatch(ctx context.Context, try func(ctx context.Context), catch func(ctx context.Context, exception error)) { 46 if try == nil { 47 return 48 } 49 if exception := Try(ctx, try); exception != nil && catch != nil { 50 catch(ctx, exception) 51 } 52 }