From 4eb8d7019fa230ebf575d32d93c692146b55c324 Mon Sep 17 00:00:00 2001 From: Shulhan Date: Sat, 26 Mar 2022 13:30:00 +0700 Subject: lib/http: use package mlog for logging In case the consumer of lib/http package use mlog for logging, the log will be written to their predefined writers. In case they did not use mlog, the log will written to stdout and stderr. --- lib/http/callback_error_handler.go | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) (limited to 'lib/http/callback_error_handler.go') diff --git a/lib/http/callback_error_handler.go b/lib/http/callback_error_handler.go index 6cd44c3e..b6e927a2 100644 --- a/lib/http/callback_error_handler.go +++ b/lib/http/callback_error_handler.go @@ -7,10 +7,10 @@ package http import ( "encoding/json" "errors" - "log" "net/http" liberrors "github.com/shuLhan/share/lib/errors" + "github.com/shuLhan/share/lib/mlog" ) // @@ -35,15 +35,21 @@ type CallbackErrorHandler func(epr *EndpointRequest) // {"code":, "message":} // func DefaultErrorHandler(epr *EndpointRequest) { - errInternal := &liberrors.E{} + var ( + logp = "DefaultErrorHandler" + errInternal = &liberrors.E{} + + jsonb []byte + err error + ) + if errors.As(epr.Error, &errInternal) { if errInternal.Code <= 0 || errInternal.Code >= 512 { errInternal.Code = http.StatusInternalServerError } } else { - log.Printf("DefaultErrorHandler: %d %s %s %s\n", - http.StatusInternalServerError, - epr.HttpRequest.Method, epr.HttpRequest.URL.Path, epr.Error) + mlog.Errf("%s: %s %s: %s", logp, epr.HttpRequest.Method, + epr.HttpRequest.URL.Path, epr.Error) errInternal = liberrors.Internal(epr.Error) } @@ -51,14 +57,14 @@ func DefaultErrorHandler(epr *EndpointRequest) { epr.HttpWriter.Header().Set(HeaderContentType, ContentTypeJSON) epr.HttpWriter.WriteHeader(errInternal.Code) - rsp, err := json.Marshal(errInternal) + jsonb, err = json.Marshal(errInternal) if err != nil { - log.Println("DefaultErrorHandler: " + err.Error()) + mlog.Errf("%s: json.Marshal: %s", logp, err) return } - _, err = epr.HttpWriter.Write(rsp) + _, err = epr.HttpWriter.Write(jsonb) if err != nil { - log.Println("DefaultErrorHandler: " + err.Error()) + mlog.Errf("%s: Write: %s", logp, err) } } -- cgit v1.3