@@ -14,6 +14,7 @@ import (
14
14
echojwt "github.com/labstack/echo-jwt/v4"
15
15
"github.com/labstack/echo/v4"
16
16
"github.com/labstack/echo/v4/middleware"
17
+ "gorm.io/gorm"
17
18
)
18
19
19
20
const (
@@ -94,10 +95,36 @@ func getAuthDetails(ctx echo.Context) *core.AuthenticationDetails {
94
95
return ctx .Get (AuthDetailsKey ).(* core.AuthenticationDetails )
95
96
}
96
97
98
+ // HTTP error handler, to handle unexpected errors
99
+ func httpErrorHandler (err error , ctx echo.Context ) {
100
+ if e , ok := err .(* echo.HTTPError ); ok {
101
+ // normal HTTP error
102
+ ctx .JSON (e .Code , e .Message )
103
+ return
104
+ }
105
+ ctx .Logger ().Error (err )
106
+ if errors .Is (err , gorm .ErrRecordNotFound ) {
107
+ ctx .NoContent (http .StatusNotFound )
108
+ } else if errors .Is (err , gorm .ErrDuplicatedKey ) {
109
+ ctx .NoContent (http .StatusConflict )
110
+ } else if errors .Is (err , core .ErrBind ) || errors .Is (err , core .ErrValidation ) {
111
+ ctx .NoContent (http .StatusUnprocessableEntity )
112
+ } else {
113
+ ctx .NoContent (http .StatusInternalServerError )
114
+ }
115
+ }
116
+
97
117
func SetupHandlers (
98
- e * echo.Echo ,
99
118
appConfig config.AppConfig ,
100
- storage_backend storage.StorageController ) error {
119
+ storage_backend storage.StorageController ) (* echo.Echo , error ) {
120
+ // Create server
121
+ e := echo .New ()
122
+ e .HTTPErrorHandler = httpErrorHandler
123
+ // Register root middleware
124
+ e .Use (middleware .Recover ())
125
+ e .Use (middleware .Logger ())
126
+ v := core.Validator {}.New ()
127
+ e .Validator = & v
101
128
corsConfig := middleware .DefaultCORSConfig
102
129
{
103
130
corsConfig .AllowOrigins = appConfig .CORSOrigins
@@ -112,7 +139,7 @@ func SetupHandlers(
112
139
)
113
140
if len (appConfig .StaticPath ) != 0 {
114
141
if _ , err := os .Stat (appConfig .StaticPath ); errors .Is (err , os .ErrNotExist ) {
115
- return err
142
+ return nil , err
116
143
}
117
144
e .Use (middleware .StaticWithConfig (middleware.StaticConfig {
118
145
Root : appConfig .StaticPath ,
@@ -134,5 +161,5 @@ func SetupHandlers(
134
161
SetupBooksHandler (apiRoutes )
135
162
SetupNotesHandler (apiRoutes , appConfig , storage_backend )
136
163
SetupAssetsHandler (apiRoutes , appConfig , storage_backend )
137
- return nil
164
+ return e , nil
138
165
}
0 commit comments