-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherrors.go
44 lines (39 loc) · 1.81 KB
/
errors.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package toolkit
import (
"fmt"
"log"
"net/http"
"runtime/debug"
)
// The serverError helper writes an error message and stack trace to the errorLog,
// then sends a generic 500 Internal Server Error response to the user.
// -- use the debug.Stack() function to get a stack trace for the current goroutine and append it to the
// -- log message. Being able to see the execution path of the
// -- application via the stack trace can be helpful when you’re trying to debug errors.
func (t *Tools) ServerError(w http.ResponseWriter, err error) {
trace := fmt.Sprintf("%s\n%s", err.Error(), debug.Stack())
// report the file name and line number one step back in the stack trace
// to have a clearer idea of where the error actually originated from
// set frame depth to 2
if t.ErrorLog != nil {
t.ErrorLog.Println(2, trace) // Use provided logger
} else {
log.Output(2, trace) // Fallback to default log package
}
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
// The clientError helper sends a specific status code and corresponding description
// to the user. We'll use this later in the book to send responses like 400
// "Bad Request" when there's a problem with the request that the user sent.
// -- use the http.StatusText() function to automatically generate a human-friendly text
// representation of a given HTTP status code. For example,
// http.StatusText(400) will return the string "Bad Request".
func (t *Tools) ClientError(w http.ResponseWriter, status int) {
http.Error(w, http.StatusText(status), status)
}
// For consistency, we'll also implement a notFound helper. This is simply a
// convenience wrapper around clientError which sends a 404 Not Found
// response to the user.
func (t *Tools) NotFound(w http.ResponseWriter) {
t.ClientError(w, http.StatusNotFound)
}