From 61395ab61b4177a4f023941fbcb86233bd889922 Mon Sep 17 00:00:00 2001 From: Sense T Date: Tue, 9 Apr 2024 21:53:12 +0800 Subject: [PATCH] errors handler --- models/record.go | 6 ++++-- server/response.go | 12 +++++++++--- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/models/record.go b/models/record.go index d55bec8..f78b27c 100644 --- a/models/record.go +++ b/models/record.go @@ -2,12 +2,14 @@ package models import ( "encoding/json" - "fmt" + "errors" "strings" dns "github.com/cloud66-oss/coredns_mysql" ) +var ErrorZoneNotEndWithDot = errors.New("zone should end with '.'") + const ( RecordTypeA = "A" RecordTypeAAAA = "AAAA" @@ -41,7 +43,7 @@ func (Record[T]) TableName() string { func (r Record[T]) CheckZone() error { if strings.HasSuffix(r.Zone, ".") { - return fmt.Errorf("zone should end with '.'") + return ErrorZoneNotEndWithDot } return nil } diff --git a/server/response.go b/server/response.go index d33859e..9b3c01f 100644 --- a/server/response.go +++ b/server/response.go @@ -3,6 +3,7 @@ package server import ( "errors" "net/http" + "reCoreD-UI/models" "github.com/gin-gonic/gin" "github.com/sirupsen/logrus" @@ -17,16 +18,21 @@ type Response struct { func errorHandler(c *gin.Context, err error) { logrus.Error(err) - if errors.Is(err, gorm.ErrRecordNotFound) { + switch { + case errors.Is(err, gorm.ErrRecordNotFound): c.JSON(http.StatusNotFound, Response{ Succeed: false, Message: err.Error(), }) - } else { + case errors.Is(err, models.ErrorZoneNotEndWithDot): + c.JSON(http.StatusBadRequest, Response{ + Succeed: false, + Message: err.Error(), + }) + default: c.JSON(http.StatusInternalServerError, Response{ Succeed: false, Message: err.Error(), - Data: nil, }) } }