...

Source file src/discovery/errors/errors.go

Documentation: discovery/errors

     1  /*
     2   * P2PFaaS - A framework for FaaS Load Balancing
     3   * Copyright (c) 2019. Gabriele Proietti Mattia <pm.gabriele@outlook.com>
     4   *
     5   * This program is free software: you can redistribute it and/or modify
     6   * it under the terms of the GNU General Public License as published by
     7   * the Free Software Foundation, either version 3 of the License, or
     8   * (at your option) any later version.
     9   *
    10   * This program is distributed in the hope that it will be useful,
    11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13   * GNU General Public License for more details.
    14   *
    15   * You should have received a copy of the GNU General Public License
    16   * along with this program.  If not, see <https://www.gnu.org/licenses/>.
    17   */
    18  
    19  // Package errors implements error management
    20  package errors
    21  
    22  import (
    23  	"encoding/json"
    24  	"io"
    25  	"net/http"
    26  )
    27  
    28  type ErrorReply struct {
    29  	Code    int    `json:"code,omitempty"`
    30  	Message string `json:"message,omitempty"`
    31  }
    32  
    33  const (
    34  	GenericError         int = 1
    35  	DBError              int = 2
    36  	GenericNotFoundError int = 3
    37  	InputNotValid        int = 4
    38  	// configuration
    39  	ConfigurationNotReady int = 100
    40  	// mongo errors
    41  	DBDuplicateKey int = 11000
    42  )
    43  
    44  var errorMessages = map[int]string{
    45  	1: "Generic Error",
    46  	2: "DB Error",
    47  	3: "Not Found",
    48  	4: "Passed input is not correct or malformed",
    49  	// configuration
    50  	100: "Configuration not ready",
    51  	// mongo
    52  	11000: "A key is duplicated",
    53  }
    54  
    55  var errorStatus = map[int]int{
    56  	1: 500,
    57  	2: 500,
    58  	3: 404,
    59  	4: 400,
    60  	// configuration
    61  	100: 500,
    62  	// mongo
    63  	11000: 400,
    64  }
    65  
    66  func ReplyWithError(w http.ResponseWriter, errorCode int) {
    67  	w.WriteHeader(errorStatus[errorCode])
    68  	var errorReply = ErrorReply{Code: errorCode, Message: errorMessages[errorCode]}
    69  	errorReplyJSON, _ := json.Marshal(errorReply)
    70  	io.WriteString(w, string(errorReplyJSON))
    71  }
    72  
    73  func ReplyWithErrorMessage(w http.ResponseWriter, errorCode int, msg string) {
    74  	w.WriteHeader(errorStatus[errorCode])
    75  	var errorReply = ErrorReply{Code: errorCode, Message: msg}
    76  	errorReplyJSON, _ := json.Marshal(errorReply)
    77  	io.WriteString(w, string(errorReplyJSON))
    78  }
    79  

View as plain text