Sobes.tech
Middle+

Where do you specify recover in the application structure (main.go, repository, service, controller)?

sobes.tech AI

Answer from AI

In Go, recover is used to catch panics and prevent the program from crashing. Typically, recover is placed where it is necessary to ensure application stability and error handling, without allowing a panic to propagate.

Most often, recover is placed:

  • At the entry point of the application — for example, in main.go inside the main function or in the root HTTP server, to catch panics that were not handled at lower levels.
  • In middleware or HTTP request handlers, to isolate a panic in one request and prevent the entire server from crashing.

In services, repositories, and business logic, recover is usually not used, as it complicates debugging and hides errors. It is better to let the panic propagate upwards and handle it centrally.

Example of usage in main.go:

func main() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered in main:", r)
            // logging, resource cleanup
        }
    }()

    // start application
}

Thus, recover is better used at application boundaries or in middleware, rather than in business logic or repositories.