2019-05-16 10:39:25 -04:00
|
|
|
package mid
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
|
2019-07-13 12:16:28 -08:00
|
|
|
"geeks-accelerator/oss/saas-starter-kit/internal/platform/web"
|
2019-08-04 14:48:43 -08:00
|
|
|
"geeks-accelerator/oss/saas-starter-kit/internal/platform/web/webcontext"
|
2019-07-31 13:47:30 -08:00
|
|
|
"geeks-accelerator/oss/saas-starter-kit/internal/platform/web/weberror"
|
2019-05-25 08:26:37 -05:00
|
|
|
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
|
2019-05-16 10:39:25 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
// Errors handles errors coming out of the call chain. It detects normal
|
|
|
|
// application errors which are used to respond to the client in a uniform way.
|
|
|
|
// Unexpected errors (status >= 500) are logged.
|
2019-08-04 14:48:43 -08:00
|
|
|
func Errors(log *log.Logger, renderer web.Renderer) web.Middleware {
|
2019-05-16 10:39:25 -04:00
|
|
|
|
|
|
|
// This is the actual middleware function to be executed.
|
|
|
|
f := func(before web.Handler) web.Handler {
|
|
|
|
|
|
|
|
// Create the handler that will be attached in the middleware chain.
|
|
|
|
h := func(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {
|
2019-05-23 19:40:29 -05:00
|
|
|
span, ctx := tracer.StartSpanFromContext(ctx, "internal.mid.Errors")
|
|
|
|
defer span.Finish()
|
2019-05-16 10:39:25 -04:00
|
|
|
|
2019-08-04 14:48:43 -08:00
|
|
|
if er := before(ctx, w, r, params); er != nil {
|
2019-05-16 10:39:25 -04:00
|
|
|
|
|
|
|
// Log the error.
|
2019-08-04 14:48:43 -08:00
|
|
|
log.Printf("%d : ERROR : %+v", span.Context().TraceID(), er)
|
2019-05-16 10:39:25 -04:00
|
|
|
|
|
|
|
// Respond to the error.
|
2019-06-26 20:21:00 -08:00
|
|
|
if web.RequestIsJson(r) {
|
2019-08-04 14:48:43 -08:00
|
|
|
if err := web.RespondJsonError(ctx, w, er); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
} else if renderer != nil {
|
|
|
|
v, err := webcontext.ContextValues(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := renderer.Error(ctx, w, r, v.StatusCode, er); err != nil {
|
2019-06-26 20:21:00 -08:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
} else {
|
2019-08-04 14:48:43 -08:00
|
|
|
if err := web.RespondError(ctx, w, er); err != nil {
|
2019-06-26 20:21:00 -08:00
|
|
|
return err
|
|
|
|
}
|
2019-05-16 10:39:25 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// If we receive the shutdown err we need to return it
|
|
|
|
// back to the base handler to shutdown the service.
|
2019-08-04 14:48:43 -08:00
|
|
|
if ok := weberror.IsShutdown(er); ok {
|
|
|
|
return er
|
2019-05-16 10:39:25 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// The error has been handled so we can stop propagating it.
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return h
|
|
|
|
}
|
|
|
|
|
|
|
|
return f
|
|
|
|
}
|