-
Notifications
You must be signed in to change notification settings - Fork 66
/
open_api_middleware.go
50 lines (44 loc) · 1.16 KB
/
open_api_middleware.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
package util
import (
"net/http"
"github.com/labstack/echo/v4"
"go.uber.org/zap"
"golang.org/x/xerrors"
)
// this is required as ipfs pinning spec has strong requirements on response format
func OpenApiMiddleware(log *zap.SugaredLogger) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
err := next(c)
if err == nil {
return nil
}
var httpRespErr *HttpError
if xerrors.As(err, &httpRespErr) {
log.Errorf("handler error: %s", err)
return c.JSON(httpRespErr.Code, &HttpErrorResponse{
Error: HttpError{
Reason: httpRespErr.Reason,
Details: httpRespErr.Details,
},
})
}
var echoErr *echo.HTTPError
if xerrors.As(err, &echoErr) {
return c.JSON(echoErr.Code, &HttpErrorResponse{
Error: HttpError{
Reason: http.StatusText(echoErr.Code),
Details: echoErr.Message.(string),
},
})
}
log.Errorf("handler error: %s", err)
return c.JSON(http.StatusInternalServerError, &HttpErrorResponse{
Error: HttpError{
Reason: http.StatusText(http.StatusInternalServerError),
Details: err.Error(),
},
})
}
}
}