github.com/lovung/GoCleanArchitecture@v0.0.0-20210302152432-50d91fd29f9f/app/internal/interface/restful/presenter/error_presenter.go (about)

     1  package presenter
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"net/http"
     7  	"strings"
     8  
     9  	"github.com/go-playground/validator/v10"
    10  )
    11  
    12  // SourceResponse an object containing references to the source of the error,
    13  // optionally including any of the following members:
    14  // - pointer: a JSON Pointer [RFC6901] to the associated entity in the
    15  // request document [e.g. "/data" for a primary data object, or
    16  // "/data/attributes/title" for a specific attribute].
    17  // - parameter: a string indicating which URI query parameter caused the error.
    18  type SourceResponse struct {
    19  	Pointer   string `json:"pointer,omitempty"`
    20  	Parameter string `json:"parameter,omitempty"`
    21  }
    22  
    23  // ErrorResponse represents the error list of the request
    24  type ErrorResponse struct {
    25  	Code   int             `json:"code,omitempty"`
    26  	Detail string          `json:"detail,omitempty"`
    27  	Source *SourceResponse `json:"source,omitempty"`
    28  }
    29  
    30  const errMsg = "Code: '%d' Detail:'%s' - Source: '%+v'"
    31  
    32  // Error method inplement built-in error interface
    33  func (e ErrorResponse) Error() string {
    34  	return fmt.Sprintf(errMsg, e.Code, e.Detail, e.Source)
    35  }
    36  
    37  // ErrorResponses is the list of ErrorResponse
    38  type ErrorResponses []ErrorResponse
    39  
    40  // Append a new error response to the list of errors
    41  func (e *ErrorResponses) Append(newE ErrorResponse) {
    42  	*e = append(*e, newE)
    43  }
    44  
    45  // Error method inplement built-in error interface
    46  func (e ErrorResponses) Error() string {
    47  	buff := bytes.NewBufferString("")
    48  
    49  	var fe ErrorResponse
    50  
    51  	for i := 0; i < len(e); i++ {
    52  		fe = e[i]
    53  		buff.WriteString(fe.Error())
    54  		buff.WriteString("\n")
    55  	}
    56  
    57  	return strings.TrimSpace(buff.String())
    58  }
    59  
    60  // FromValidationErrors converts from validator.ValidationErrors to presenter.ErrorResponse
    61  func (e *ErrorResponses) FromValidationErrors(vldErrs validator.ValidationErrors) {
    62  	for i := range vldErrs {
    63  		*e = append(*e, ErrorResponse{
    64  			Code:   http.StatusUnprocessableEntity,
    65  			Detail: vldErrs.Error(),
    66  			Source: &SourceResponse{
    67  				Pointer:   vldErrs[i].StructNamespace(),
    68  				Parameter: vldErrs[i].StructField(),
    69  			},
    70  		})
    71  	}
    72  }