Home >Backend Development >Golang >How to handle exceptions in Goroutine?
Handling exceptions in Goroutine: Use recover to get the exception from the recovery point. Handle exceptions within defer statements, such as a print-friendly errorMessage. Practical case: Asynchronously check user access permissions and capture exceptions with insufficient permissions, and display friendly messages to users.
#How to handle exceptions in Goroutine?
In concurrent programming, coroutines or Goroutines are lightweight threads that execute independently. However, handling exceptions in Goroutines is not quite the same as with traditional threads.
Handling exceptions in Goroutine
First, let us create a Goroutine:
func main() { go func() { // 可能会抛出异常的代码 }() }
Go does not catch exceptions in Goroutine by default. If the Goroutine throws an exception, the program will crash. In order to handle the exception, we need to use the recover
function:
func main() { go func() { defer func() { if r := recover(); r != nil { // 处理异常 fmt.Println("捕获到异常:", r) } }() }() }
Inside the defer
statement, we use recover
to get the exception from the recovery point and Process it as needed.
Practical Case: Accessing Protected Resources
Suppose we have a protected resource that only users with specific access permissions can access it. We can use Goroutine to check the user's permissions asynchronously:
func checkAccess(userId int) error { user, err := getUserByID(userId) if err != nil { return err } if user.accessLevel != ADMIN { return errors.New("没有访问权限") } return nil } func main() { userIDs := []int{1, 2, 3} for _, id := range userIDs { go func(userId int) { if err := checkAccess(userId); err != nil { defer func() { if r := recover(); r != nil { // 处理异常:权限不足 fmt.Println("用户", userId, ": 权限不足") } }() panic(err) } fmt.Println("用户", userId, ": 有访问权限") }(id) } }
In this example, Goroutine may throw an errors.New("No access permission")
exception, which will cause the program to collapse. By using the defer
statement and the recover
function, we are able to catch the exception and display a friendly errorMessage to the user.
The above is the detailed content of How to handle exceptions in Goroutine?. For more information, please follow other related articles on the PHP Chinese website!