goext/exerr/gin.go
2023-07-24 11:11:15 +02:00

85 lines
1.8 KiB
Go

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