Handling Panics
In Go applications, panics can occur during runtime when something unexpected happens. This guide explains how to handle panics both in general Go code and specifically in your Wails application.
Understanding Panics in Go
Before diving into Wails-specific panic handling, it’s essential to understand how panics work in Go:
- Panics are for unrecoverable errors that shouldn’t happen during normal operation
- When a panic occurs in a goroutine, only that goroutine is affected
- Panics can be recovered using
defer
andrecover()
Here’s a basic example of panic handling in Go:
For more detailed information about panic and recover in Go, see the Go Blog: Defer, Panic, and Recover.
Panic Handling in Wails
Wails automatically handles panics that occur in your Service methods when they are called from the frontend. This means you don’t need to add panic recovery to these methods - Wails will catch the panic and process it through your configured panic handler.
The panic handler is specifically designed to catch:
- Panics in bound service methods called from the frontend
- Internal panics from the Wails runtime
For other scenarios, such as background goroutines or standalone Go code, you should handle panics yourself using Go’s standard panic recovery mechanisms.
The PanicDetails Struct
When a panic occurs, Wails captures important information about the panic in a PanicDetails
struct:
This structure provides comprehensive information about the panic:
StackTrace
: A formatted string showing the call stack that led to the panicError
: The actual error or panic messageTime
: The exact time when the panic occurredFullStackTrace
: The complete stack trace including runtime frames
Default Panic Handler
If you don’t specify a custom panic handler, Wails will use its default handler which outputs error information in a formatted log message. For example:
Custom Panic Handler
You can implement your own panic handler by setting the PanicHandler
option when creating your application. Here’s an example:
For a complete working example of panic handling in a Wails application, see the panic-handling example in v3/examples/panic-handling
.
Final Notes
Remember that the Wails panic handler is specifically for managing panics in bound methods and internal runtime errors. For other parts of your application, you should use Go’s standard error handling patterns and panic recovery mechanisms where appropriate. As with all Go applications, it’s better to prevent panics through proper error handling where possible.