github.com/datadog/cilium@v1.6.12/pkg/api/apierror.go (about)

     1  // Copyright 2016-2018 Authors of Cilium
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package api
    16  
    17  import (
    18  	"fmt"
    19  	"net/http"
    20  
    21  	"github.com/cilium/cilium/api/v1/models"
    22  
    23  	"github.com/go-openapi/runtime"
    24  )
    25  
    26  // APIError is the error representation for the API.
    27  type APIError struct {
    28  	code int
    29  	msg  string
    30  }
    31  
    32  // New creates a API error from the code, msg and extra arguments.
    33  func New(code int, msg string, args ...interface{}) *APIError {
    34  	if code <= 0 {
    35  		code = 500
    36  	}
    37  
    38  	if len(args) > 0 {
    39  		return &APIError{code: code, msg: fmt.Sprintf(msg, args...)}
    40  	}
    41  	return &APIError{code: code, msg: msg}
    42  }
    43  
    44  // Error creates a new API error from the code and error.
    45  func Error(code int, err error) *APIError {
    46  	if err == nil {
    47  		err = fmt.Errorf("Error pointer was nil")
    48  	}
    49  
    50  	return New(code, err.Error())
    51  }
    52  
    53  // Error returns the API error message.
    54  func (a *APIError) Error() string {
    55  	return a.msg
    56  }
    57  
    58  // GetModel returns model error.
    59  func (a *APIError) GetModel() *models.Error {
    60  	m := models.Error(a.msg)
    61  	return &m
    62  }
    63  
    64  // WriteResponse to the client.
    65  func (a *APIError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
    66  	rw.WriteHeader(a.code)
    67  	m := a.GetModel()
    68  	if err := producer.Produce(rw, m); err != nil {
    69  		panic(err)
    70  	}
    71  
    72  }