src

Go monorepo.
git clone git://code.dwrz.net/src
Log | Files | Refs

error.go (1045B)


      1 package site
      2 
      3 import (
      4 	"bytes"
      5 	"fmt"
      6 	"net/http"
      7 	"runtime/debug"
      8 
      9 	"code.dwrz.net/src/cmd/web/site/page"
     10 )
     11 
     12 const (
     13 	defaultErrorMessage = "Sorry, something went wrong."
     14 )
     15 
     16 type Error struct {
     17 	Code    int
     18 	Error   error
     19 	Message string
     20 }
     21 
     22 func (s *Site) error(w http.ResponseWriter, r *http.Request, e *Error) {
     23 	var (
     24 		id    = r.Context().Value("id").(string)
     25 		trace = string(debug.Stack())
     26 	)
     27 
     28 	// Log with the line number of the caller.
     29 	s.log.Error.Output(
     30 		2,
     31 		fmt.Sprintf("%s → %d error: %v", id, e.Code, e.Error),
     32 	)
     33 	if s.debug {
     34 		s.log.Error.Output(2, fmt.Sprintf(
     35 			"%s → TRACE:\n%s\n", id, trace,
     36 		))
     37 	}
     38 
     39 	var p = &bytes.Buffer{}
     40 	if err := s.tmpl.ExecuteTemplate(
     41 		p, "base", &page.Error{
     42 			Debug:     s.debug,
     43 			Message:   e.Message,
     44 			RequestId: id,
     45 			Text:      e.Error.Error(),
     46 			Trace:     trace,
     47 		},
     48 	); err != nil {
     49 		s.log.Error.Printf("%s → failed to render page: %v", id, err)
     50 
     51 		w.WriteHeader(e.Code)
     52 		w.Write([]byte(defaultErrorMessage))
     53 		return
     54 	}
     55 
     56 	w.WriteHeader(e.Code)
     57 	w.Write(p.Bytes())
     58 }