Go · Level 2 Errors

Defer and Recover

Catch a panicking HTTP handler with defer and recover in Go and turn it into an error, so one bad request can't crash the whole server.

  • defer runs when the function returns
  • recover() stops a panic
  • set a named result inside the deferred function

defer runs a function when the surrounding one returns, even after a panic, and recover() inside it stops the panic. Trap: recover works only when called directly in a deferred function; anywhere else it returns nil.

func safe() (err error) {
    defer func() {
        if r := recover(); r != nil {
            err = fmt.Errorf("caught: %v", r)
        }
    }()
    panic("boom")
}

Write Serve(handler func(int) int, n int) (result int, err error): return handler(n), or if it panics, 0 and the error "handler panicked: <value>". Example: a handler that panics with "db down" → 0, handler panicked: db down.

solution.go
Test Suites Pending
Output