Implementing HTTP error handling in Go
Implementing error handling in any web application is one of the main aspects because it helps in troubleshooting and fixing bugs faster. Error handling means whenever an error occurs in an application, it should be logged somewhere, either in a file or in a database with the proper error message, along with the stack trace.
In Go, it can be implemented in multiple ways. One way is to write custom handlers, which we will be covering in this recipe.
How to do it…
- Install the
github.com/gorilla/mux
package using thego get
command, as follows:
$ go get github.com/gorilla/mux
- Create
http-error-handling.go
, where we will create a custom handler that acts as a wrapper to handle all the HTTP requests, as follows:
package main import ( "errors" "fmt" "log" "net/http" "strings" "github.com/gorilla/mux" ) const ( CONN_HOST = "localhost" CONN_PORT = "8080" ) type NameNotFoundError struct { Code int Err error } func (nameNotFoundError NameNotFoundError...