goext/exerr/gin.go
2023-07-24 12:27:06 +02:00

86 lines
1.9 KiB
Go

package exerr
import (
"github.com/gin-gonic/gin"
json "gogs.mikescher.com/BlackForestBytes/goext/gojson"
"net/http"
"time"
)
func (ee *ExErr) toJson(depth int) gin.H {
ginJson := gin.H{}
if ee.UniqueID != "" {
ginJson["id"] = ee.UniqueID
}
if ee.Category != CatWrap {
ginJson["category"] = ee.Category
}
if ee.Type != TypeWrap {
ginJson["type"] = ee.Type
}
if ee.StatusCode != nil {
ginJson["statuscode"] = ee.StatusCode
}
if ee.Message != "" {
ginJson["message"] = ee.Message
}
if ee.Caller != "" {
ginJson["caller"] = ee.Caller
}
if ee.Severity != SevErr {
ginJson["severity"] = ee.Severity
}
if ee.Timestamp != (time.Time{}) {
ginJson["time"] = ee.Timestamp.Format(time.RFC3339)
}
if ee.WrappedErrType != "" {
ginJson["wrappedErrType"] = ee.WrappedErrType
}
if ee.OriginalError != nil {
ginJson["original"] = ee.OriginalError.toJson(depth + 1)
}
pkgconfig.ExtendGinDataOutput(ee, depth, ginJson)
return ginJson
}
func (ee *ExErr) Output(g *gin.Context) {
var statuscode = http.StatusInternalServerError
var baseCat = ee.RecursiveCategory()
var baseType = ee.RecursiveType()
var baseStatuscode = ee.RecursiveStatuscode()
var baseMessage = ee.RecursiveMessage()
if baseCat == CatUser {
statuscode = http.StatusBadRequest
} else if baseCat == CatSystem {
statuscode = http.StatusInternalServerError
}
if baseStatuscode != nil {
statuscode = *ee.StatusCode
} else if baseType.DefaultStatusCode != nil {
statuscode = *baseType.DefaultStatusCode
}
warnOnPkgConfigNotInitialized()
ginOutput := gin.H{
"errorid": ee.UniqueID,
"message": baseMessage,
"errorcode": baseType.Key,
"category": baseCat.Category,
}
if pkgconfig.ExtendedGinOutput {
ginOutput["__data"] = ee.toJson(0)
}
pkgconfig.ExtendGinOutput(ee, ginOutput)
g.Render(statuscode, json.GoJsonRender{Data: ginOutput, NilSafeSlices: true, NilSafeMaps: true})
}