...

Source file src/go.formulabun.club/translator/server/go/error.go

Documentation: go.formulabun.club/translator/server/go

     1  /*
     2   * Translator service between a srb2kart server and json
     3   *
     4   * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
     5   *
     6   * API version: 0.0.1
     7   * Generated by: OpenAPI Generator (https://openapi-generator.tech)
     8   */
     9  
    10  package openapi
    11  
    12  import (
    13  	"errors"
    14  	"fmt"
    15  	"net/http"
    16  )
    17  
    18  var (
    19  	// ErrTypeAssertionError is thrown when type an interface does not match the asserted type
    20  	ErrTypeAssertionError = errors.New("unable to assert type")
    21  )
    22  
    23  // ParsingError indicates that an error has occurred when parsing request parameters
    24  type ParsingError struct {
    25  	Err error
    26  }
    27  
    28  func (e *ParsingError) Unwrap() error {
    29  	return e.Err
    30  }
    31  
    32  func (e *ParsingError) Error() string {
    33  	return e.Err.Error()
    34  }
    35  
    36  // RequiredError indicates that an error has occurred when parsing request parameters
    37  type RequiredError struct {
    38  	Field string
    39  }
    40  
    41  func (e *RequiredError) Error() string {
    42  	return fmt.Sprintf("required field '%s' is zero value.", e.Field)
    43  }
    44  
    45  // ErrorHandler defines the required method for handling error. You may implement it and inject this into a controller if
    46  // you would like errors to be handled differently from the DefaultErrorHandler
    47  type ErrorHandler func(w http.ResponseWriter, r *http.Request, err error, result *ImplResponse)
    48  
    49  // DefaultErrorHandler defines the default logic on how to handle errors from the controller. Any errors from parsing
    50  // request params will return a StatusBadRequest. Otherwise, the error code originating from the servicer will be used.
    51  func DefaultErrorHandler(w http.ResponseWriter, r *http.Request, err error, result *ImplResponse) {
    52    fmt.Println(err)
    53  	if _, ok := err.(*ParsingError); ok {
    54  		// Handle parsing errors
    55  		EncodeJSONResponse(err.Error(), func(i int) *int { return &i }(http.StatusBadRequest), w)
    56  	} else if _, ok := err.(*RequiredError); ok {
    57  		// Handle missing required errors
    58  		EncodeJSONResponse(err.Error(), func(i int) *int { return &i }(http.StatusUnprocessableEntity), w)
    59  	} else {
    60  		// Handle all other errors
    61  		EncodeJSONResponse(err.Error(), &result.Code, w)
    62  	}
    63  }
    64  

View as plain text