-
Notifications
You must be signed in to change notification settings - Fork 8
/
recovery.go
56 lines (51 loc) · 2.06 KB
/
recovery.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
45
46
47
48
49
50
51
52
53
54
55
56
// Copyright 2016 Qiang Xue. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
// Package fault provides a panic and error handler for the ozzo routing package.
package fault
import "github.com/jackwhelpton/fasthttp-routing/v2"
type (
// LogFunc logs a message using the given format and optional arguments.
// The usage of format and arguments is similar to that for fmt.Printf().
// LogFunc should be thread safe.
LogFunc func(format string, a ...interface{})
// ConvertErrorFunc converts an error into a different format so that it is more appropriate for rendering purpose.
ConvertErrorFunc func(*routing.Context, error) error
)
// Recovery returns a handler that handles both panics and errors occurred while servicing an HTTP request.
// Recovery can be considered as a combination of ErrorHandler and PanicHandler.
//
// The handler will recover from panics and render the recovered error or the error returned by a handler.
// If the error implements routing.HTTPError, the handler will set the HTTP status code accordingly.
// Otherwise the HTTP status is set as fasthttp.StatusInternalServerError. The handler will also write the error
// as the response body.
//
// A log function can be provided to log a message whenever an error is handled. If nil, no message will be logged.
//
// An optional error conversion function can also be provided to convert an error into a normalized one
// before sending it to the response.
//
// import (
// "log"
// "github.com/jackwhelpton/fasthttp-routing/v2"
// "github.com/jackwhelpton/fasthttp-routing/v2/fault"
// )
//
// r := routing.New()
// r.Use(fault.Recovery(log.Printf))
func Recovery(logf LogFunc, errorf ...ConvertErrorFunc) routing.Handler {
handlePanic := PanicHandler(logf)
return func(c *routing.Context) error {
if err := handlePanic(c); err != nil {
if logf != nil {
logf("%v", err)
}
if len(errorf) > 0 {
err = errorf[0](c, err)
}
writeError(c, err)
c.Abort()
}
return nil
}
}