github.com/gocaveman/caveman@v0.0.0-20191211162744-0ddf99dbdf6e/webutil/http-error.go (about)

     1  package webutil
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"log"
     7  	"math/rand"
     8  	"net/http"
     9  	"runtime"
    10  	"time"
    11  )
    12  
    13  // HTTPError reports an error - does not expose anything to the outside
    14  // world except a unique ID, which can be matched up with the appropriate log
    15  // statement which has the details.
    16  func HTTPError(w http.ResponseWriter, r *http.Request, err error, publicMessage string, code int) error {
    17  
    18  	if err == nil {
    19  		err = errors.New(publicMessage)
    20  	}
    21  
    22  	id := fmt.Sprintf("%x", time.Now().Unix()^rand.Int63())
    23  
    24  	_, file, line, _ := runtime.Caller(1)
    25  
    26  	w.Header().Set("x-error-id", id) // make a way for the client to programatically extract the error id
    27  	http.Error(w, fmt.Sprintf("Error serving request (id=%q) %s", id, publicMessage), code)
    28  
    29  	log.Printf("HTTPError: (id=%q) %s:%v | %v", id, file, line, err)
    30  
    31  	return err
    32  }