programming

05 Learn About Panic Handler

Understanding Panic Handlers

When we create logic in the handler, we must think of a case where panic occurs, then what should we do? In this Panic handler an error will automatically occur and the website will stop returning responses. In the previous material, we discussed how the Web handles panic by creating special Middleware manually. However, the Router has been provided to handle panic by using the PanicHandler attribute.

func(http.ResponseWriter, *http.Request, interface{})

How to Implement

When implementing Panic Handler we need to create a PanicHandler router as below in the main.go file.

router.PanicHandler = func(w http.ResponseWriter, r *http.Request, i interface{}) {
	fmt.Fprint(w, "Panic ", i)
}

Next, we will create a handler whose contents directly address the panic situation using the panic() function as below.

func PanicHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	panic("Oops panic")
}

After that, we also add to the main.go Router initialization file so that the handler we have created above can be read by the router and later we will try to access the endpoint as a simulation.

router.GET("/panic", PanicHandler)

If you have added the above then we just have to try to run our program or project with this command.

go build && ./learn-golang-httprouter

Next, we try to access the endpoint that we have created using the cURL below and the results will come out according to the panic definition that we have created.

➜  santekno-hugo git:(main) ✗ curl --location --request GET 'http://localhost:8080/panic'
Panic Oops panic%

If we create a panic handler like the one above, our service or project will not stop because the panic handler we have created will not cause the program to stop. So this is very beneficial if we have many endpoints in one project and then one of the endpoints panics, the service will not go down and it will also not interfere with other endpoints because our service or program will continue to run as usual.

comments powered by Disqus