DEV Community

Clavin June
Clavin June

Posted on • Originally published at clavinjune.dev on

3 2

Golang Panic Handler Middleware

Sunday Snippet #2 go get golang private module

Handling panic elegantly:

package main

import (
    "fmt"
    "log"
    "net/http"
)

func handle() http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        panic("i am panic")
    }
}

func handlePanic(next http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        defer func() {
            if i := recover(); i != nil {
                log.Printf("panic at %s: %v", r.URL.Path, i)
                w.WriteHeader(http.StatusInternalServerError)
                fmt.Fprint(w, http.StatusText(http.StatusInternalServerError))
            }
        }()

        next(w, r)
    }
}

func main() {
    http.ListenAndServe(":8000", handlePanic(handle()))
}
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay