How to use getErrorMessage method of api Package

Best Gauge code snippet using api.getErrorMessage

proxy.go

Source:proxy.go Github

copy

Full Screen

...56 }57 if workerRequestID, err := ph.checkAuthorization(r, urn, proxyResource.Resource.Action); err == nil {58 destURL, err := url.Parse(proxyResource.Resource.Host)59 if err != nil {60 apiErr := getErrorMessage(INVALID_DEST_HOST_URL, fmt.Sprintf("Error creating destination host URL: %v", err.Error()))61 api.TransactionProxyErrorLogWithStatus(requestID, workerRequestID, r, http.StatusInternalServerError, apiErr)62 WriteHttpResponse(r, w, requestID, "", http.StatusInternalServerError, getErrorMessage(INVALID_DEST_HOST_URL, "Error creating destination host"))63 return64 }65 // Log request66 api.TransactionProxyLog(requestID, workerRequestID, r, "Request accepted")67 // Serve Request68 reverseProxy := httputil.NewSingleHostReverseProxy(destURL)69 logWritter := api.Log.Writer()70 defer logWritter.Close()71 reverseProxy.ErrorLog = log.New(logWritter, "", 0)72 reverseProxy.FlushInterval = ph.proxy.ProxyFlushInterval73 reverseProxy.ServeHTTP(w, r)74 } else {75 apiError := err.(*api.Error)76 var statusCode int77 var responseErr *api.Error78 switch apiError.Code {79 case FORBIDDEN_ERROR:80 statusCode = http.StatusForbidden81 responseErr = getErrorMessage(FORBIDDEN_ERROR, "")82 case api.INVALID_PARAMETER_ERROR, api.REGEX_NO_MATCH, BAD_REQUEST:83 statusCode = http.StatusBadRequest84 responseErr = getErrorMessage(api.INVALID_PARAMETER_ERROR, "Bad request")85 default:86 statusCode = http.StatusInternalServerError87 responseErr = getErrorMessage(INTERNAL_SERVER_ERROR, "Internal server error. Contact the administrator")88 }89 WriteHttpResponse(r, w, requestID, "", statusCode, responseErr)90 api.TransactionProxyErrorLogWithStatus(requestID, workerRequestID, r, statusCode, apiError)91 return92 }93 }94}95// HANDLERS96func (wh *WorkerHandler) HandleAddProxyResource(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {97 // Process request98 request := &CreateProxyResourceRequest{}99 requestInfo, filterData, apiErr := wh.processHttpRequest(r, w, ps, request)100 if apiErr != nil {101 wh.processHttpResponse(r, w, requestInfo, nil, apiErr, http.StatusBadRequest)102 return103 }104 // Call proxy Resource API to create proxyResource105 response, err := wh.worker.ProxyApi.AddProxyResource(requestInfo, request.Name, filterData.Org, request.Path, request.Resource)106 wh.processHttpResponse(r, w, requestInfo, response, err, http.StatusCreated)107}108func (wh *WorkerHandler) HandleGetProxyResourceByName(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {109 // Process request110 requestInfo, filterData, apiErr := wh.processHttpRequest(r, w, ps, nil)111 if apiErr != nil {112 wh.processHttpResponse(r, w, requestInfo, nil, apiErr, http.StatusBadRequest)113 return114 }115 // Call policy API to retrieve policy116 response, err := wh.worker.ProxyApi.GetProxyResourceByName(requestInfo, filterData.Org, filterData.ProxyResourceName)117 wh.processHttpResponse(r, w, requestInfo, response, err, http.StatusOK)118}119func (wh *WorkerHandler) HandleListProxyResource(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {120 // Process request121 requestInfo, filterData, apiErr := wh.processHttpRequest(r, w, ps, nil)122 if apiErr != nil {123 wh.processHttpResponse(r, w, requestInfo, nil, apiErr, http.StatusBadRequest)124 return125 }126 // Call proxy Resource API to create proxyResource127 result, total, err := wh.worker.ProxyApi.ListProxyResources(requestInfo, filterData)128 proxyResources := []string{}129 for _, proxyResource := range result {130 proxyResources = append(proxyResources, proxyResource.Name)131 }132 // Create response133 response := &ListProxyResourcesResponse{134 Resources: proxyResources,135 Offset: filterData.Offset,136 Limit: filterData.Limit,137 Total: total,138 }139 wh.processHttpResponse(r, w, requestInfo, response, err, http.StatusOK)140}141func (wh *WorkerHandler) HandleUpdateProxyResource(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {142 // Process request143 request := &UpdateProxyResourceRequest{}144 requestInfo, filterData, apiErr := wh.processHttpRequest(r, w, ps, request)145 if apiErr != nil {146 wh.processHttpResponse(r, w, requestInfo, nil, apiErr, http.StatusBadRequest)147 return148 }149 // Call proxy resource API to update proxy resource150 response, err := wh.worker.ProxyApi.UpdateProxyResource(requestInfo, filterData.Org, filterData.ProxyResourceName, request.Name, request.Path, request.Resource)151 wh.processHttpResponse(r, w, requestInfo, response, err, http.StatusOK)152}153func (wh *WorkerHandler) HandleRemoveProxyResource(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {154 // Process request155 requestInfo, filterData, apiErr := wh.processHttpRequest(r, w, ps, nil)156 if apiErr != nil {157 wh.processHttpResponse(r, w, requestInfo, nil, apiErr, http.StatusBadRequest)158 return159 }160 // Call proxy resource API to remove proxy resource161 err := wh.worker.ProxyApi.RemoveProxyResource(requestInfo, filterData.Org, filterData.ProxyResourceName)162 wh.processHttpResponse(r, w, requestInfo, nil, err, http.StatusNoContent)163}164func (ph *ProxyHandler) checkAuthorization(r *http.Request, urn string, action string) (string, error) {165 workerRequestID := "None"166 if !isFullUrn(urn) {167 return workerRequestID,168 getErrorMessage(api.INVALID_PARAMETER_ERROR, fmt.Sprintf("Urn %v is a prefix, it would be a full urn resource", urn))169 }170 if err := api.AreValidResources([]string{urn}, api.RESOURCE_EXTERNAL); err != nil {171 return workerRequestID, err172 }173 if err := api.AreValidActions([]string{action}); err != nil {174 return workerRequestID, err175 }176 body, err := json.Marshal(AuthorizeResourcesRequest{177 Action: action,178 Resources: []string{urn},179 })180 if err != nil {181 return workerRequestID, getErrorMessage(api.UNKNOWN_API_ERROR, err.Error())182 }183 req, err := http.NewRequest(http.MethodPost, ph.proxy.WorkerHost+RESOURCE_URL, bytes.NewBuffer(body))184 if err != nil {185 return workerRequestID, getErrorMessage(api.UNKNOWN_API_ERROR, err.Error())186 }187 // Add all headers from original request188 req.Header = r.Header189 // Call worker to retrieve authorization190 res, err := ph.client.Do(req)191 if err != nil {192 return workerRequestID, getErrorMessage(HOST_UNREACHABLE, err.Error())193 }194 defer res.Body.Close()195 workerRequestID = res.Header.Get(middleware.REQUEST_ID_HEADER)196 switch res.StatusCode {197 case http.StatusUnauthorized:198 return workerRequestID, getErrorMessage(FORBIDDEN_ERROR, "Unauthenticated user")199 case http.StatusForbidden:200 return workerRequestID, getErrorMessage(FORBIDDEN_ERROR, fmt.Sprintf("Restricted access to urn %v", urn))201 case http.StatusBadRequest:202 return workerRequestID, getErrorMessage(BAD_REQUEST, "Invalid request")203 case http.StatusOK:204 authzResponse := AuthorizeResourcesResponse{}205 err = json.NewDecoder(res.Body).Decode(&authzResponse)206 if err != nil {207 return workerRequestID, getErrorMessage(api.UNKNOWN_API_ERROR, fmt.Sprintf("Error parsing foulkon response %v", err.Error()))208 }209 // Check urns allowed to find target urn210 allowed := false211 for _, allowedRes := range authzResponse.ResourcesAllowed {212 if allowedRes == urn {213 allowed = true214 break215 }216 }217 if !allowed {218 return workerRequestID,219 getErrorMessage(FORBIDDEN_ERROR, fmt.Sprintf("No access for urn %v received from server", urn))220 }221 return workerRequestID, nil222 default:223 return workerRequestID,224 getErrorMessage(INTERNAL_SERVER_ERROR, fmt.Sprintf("There was a problem retrieving authorization, status code %v", res.StatusCode))225 }226}227// Check parameters in URN to replace with URI parameters228func getUrnParameters(urn string) [][]string {229 match := rUrnParam.FindAllStringSubmatch(urn, -1)230 if match != nil && len(match) > 0 {231 return match232 }233 return nil234}235func isFullUrn(resource string) bool {236 return !strings.ContainsAny(resource, "*")237}238func getErrorMessage(errorCode string, message string) *api.Error {239 if message == "" {240 return &api.Error{241 Code: errorCode,242 Message: "Forbidden resource. If you need access, contact the administrator",243 }244 }245 return &api.Error{246 Code: errorCode,247 Message: message,248 }249}...

Full Screen

Full Screen

main.go

Source:main.go Github

copy

Full Screen

...33 span.AddField("url", apiURL)34 url := fmt.Sprintf("%s/%s", apiURL, event.Planet)35 req, err := http.NewRequest("GET", url, nil)36 if err != nil {37 return getErrorMessage(ctx, err)38 }39 req.Header.Set("X-Honeycomb-Trace", span.SerializeHeaders())40 client := &http.Client{}41 res, err := client.Do(req)42 if err != nil {43 span.AddField("error", err)44 return getErrorMessage(ctx, err)45 }46 defer res.Body.Close()47 if res.StatusCode != http.StatusOK {48 span.AddField("upstreamError", res.StatusCode)49 bodyBytes, _ := ioutil.ReadAll(res.Body)50 message := string(bodyBytes)51 span.AddField("upstreamBody", message)52 return getErrorMessage(ctx, fmt.Errorf("%d - %s", res.StatusCode, message))53 }54 r := new(weatheraryResponse)55 err = json.NewDecoder(res.Body).Decode(r)56 span.AddField("planetary", res)57 if err != nil {58 return getErrorMessage(ctx, err)59 }60 defer span.Send()61 return r.Weather62}63// Response is of type APIGatewayProxyResponse since we're leveraging the64// AWS Lambda Proxy Request functionality (default behavior)65//66// https://serverless.com/framework/docs/providers/aws/events/apigateway/#lambda-proxy-integration67type Response events.APIGatewayProxyResponse68// Handler is the lambda handler invoked by the `lambda.Start` function call69func Handler(ctx context.Context, event weatherRequestEvent) (Response, error) {70 ctx, span := beeline.StartSpan(ctx, "Handler")71 defer span.Send()72 span.AddField("city", event.City)73 var result string74 if len(event.Planet) > 0 {75 result = getPlanetaryWeather(ctx, event)76 } else {77 result = getWeather(ctx, event.City)78 }79 var buf bytes.Buffer80 body, err := json.Marshal(map[string]interface{}{81 "city": event.City,82 "weather": result,83 })84 if err != nil {85 return Response{StatusCode: 404}, err86 }87 json.HTMLEscape(&buf, body)88 resp := Response{89 StatusCode: 200,90 IsBase64Encoded: false,91 Body: buf.String(),92 Headers: map[string]string{93 "Content-Type": "application/json",94 },95 }96 return resp, nil97}98func getErrorMessage(ctx context.Context, err error) string {99 _, span := beeline.StartSpan(ctx, "getError")100 span.AddField("error", err.Error())101 defer span.Send()102 return err.Error()103}104func getWeather(ctx context.Context, city string) string {105 var apiKey = os.Getenv("OWM_API_KEY")106 ctx, span := beeline.StartSpan(ctx, "getWeather")107 defer span.Send()108 w, err := owm.NewCurrent("C", "en", apiKey)109 if err != nil {110 return getErrorMessage(ctx, err)111 }112 w.CurrentByName(city)113 if len(w.Weather) == 0 {114 return getErrorMessage(ctx, errors.New("City not found"))115 }116 result := w.Weather[0].Description117 span.AddField("weather", result)118 return result119}120func main() {121 beeline.Init(beeline.Config{122 WriteKey: os.Getenv("HONEYCOMB_KEY"),123 Dataset: os.Getenv("HONEYCOMB_DATASET"),124 })125 lambda.Start(HoneycombMiddleware(Handler))126}127func addRequestProperties(ctx context.Context) {128 // Add a variety of details about the lambda request...

Full Screen

Full Screen

user-controller.go

Source:user-controller.go Github

copy

Full Screen

1package controllers2import (3 "blog-api-golang/cache"4 "blog-api-golang/models"5 "blog-api-golang/services"6 "blog-api-golang/types"7 "blog-api-golang/utils"8 "net/http"9 "time"10 "github.com/gin-gonic/gin"11)12func SignInHandler(c *gin.Context) {13 var signInRequest types.SignInRequest14 if c.Bind(&signInRequest) != nil {15 c.JSON(http.StatusBadRequest, utils.GetErrorMessage("Invalid Params"))16 }17 userInfo, err := models.GetUserInfo(signInRequest.Email)18 if err != nil {19 c.JSON(http.StatusForbidden, utils.GetErrorMessage("Username is not existed"))20 return21 }22 check := utils.CheckPasswordHash(signInRequest.Password, userInfo.Password)23 if !check {24 c.JSON(http.StatusForbidden, utils.GetErrorMessage("Username/ Password is not correct"))25 return26 }27 jwtToken, err := utils.GenerateJWT(userInfo.Email, userInfo.Role)28 if err != nil {29 c.JSON(http.StatusForbidden, utils.GetErrorMessage("Username/ Password is not correct"))30 return31 }32 c.JSON(http.StatusOK, utils.GetSuccessMessage(types.AuthenticateResp{33 Email: userInfo.Email,34 PrivateToken: jwtToken,35 Role: userInfo.Role,36 }))37}38func CreateAccountHandler(c *gin.Context) {39 var createAccountReq types.CreateAccountRequest40 if c.Bind(&createAccountReq) != nil {41 c.JSON(http.StatusBadRequest, utils.GetErrorMessage("Invalid Params"))42 }43 if createAccountReq.Role == "" {44 createAccountReq.Role = utils.USER45 }46 userInfo, _ := models.GetUserInfo(createAccountReq.Email)47 if userInfo.Email != "" {48 c.JSON(http.StatusForbidden, utils.GetErrorMessage("Email already existed"))49 return50 }51 createdUser, err := models.CreateUser(createAccountReq.Email, createAccountReq.Password, createAccountReq.Role)52 if err != nil {53 c.JSON(http.StatusForbidden, utils.GetErrorMessage("Fail to create"))54 return55 }56 mailList := []string{createdUser.Email}57 otp := utils.OTPGenerator()58 if ok := cache.SetValue(createdUser.Email, otp, time.Minute*5); !ok {59 c.JSON(http.StatusBadRequest, utils.GetErrorMessage("Error when generate OTP"))60 }61 mailService := services.CreateNewMail(mailList, "Welcome to The Bidu family")62 err = mailService.SendMail("template/register.html", types.RegisterTemplateItems{63 Email: createdUser.Email,64 OTP: otp,65 })66 if err != nil {67 c.JSON(http.StatusBadRequest, utils.GetErrorMessage("Sent OTP Fail with Error "+err.Error()))68 return69 }70 c.JSON(http.StatusCreated, createdUser)71}72func GetUserInfoHandler(c *gin.Context) {73 userEmail := c.GetHeader("email")74 if userEmail == "" {75 c.JSON(http.StatusForbidden, utils.GetErrorMessage("User is not existed"))76 return77 }78 userInfo, err := models.GetUserInfo(userEmail)79 if err != nil {80 c.JSON(http.StatusForbidden, utils.GetErrorMessage("User is not existed"))81 return82 }83 c.JSON(http.StatusOK, utils.GetSuccessMessage(userInfo))84}85func GetAllUserHandler(c *gin.Context) {86 userList, err := models.GetAllUser()87 if err != nil {88 c.JSON(http.StatusForbidden, utils.GetErrorMessage(err.Error()))89 return90 }91 c.JSON(http.StatusOK, utils.GetSuccessMessage(userList))92}...

Full Screen

Full Screen

getErrorMessage

Using AI Code Generation

copy

Full Screen

1func main() {2 fmt.Println(api.getErrorMessage())3}4func main() {5 fmt.Println(api.getErrorMessage())6}7func main() {8 fmt.Println(api.getErrorMessage())9}10func main() {11 fmt.Println(api.getErrorMessage())12}13func main() {14 fmt.Println(api.getErrorMessage())15}16func main() {17 fmt.Println(api.getErrorMessage())18}19func main() {20 fmt.Println(api.getErrorMessage())21}22func main() {23 fmt.Println(api.getErrorMessage())24}25func main() {26 fmt.Println(api.getErrorMessage())27}28func main() {29 fmt.Println(api.getErrorMessage())30}31func main() {32 fmt.Println(api.getErrorMessage())33}34func main() {35 fmt.Println(api.getErrorMessage())36}37func main() {38 fmt.Println(api.getErrorMessage())39}40func main() {41 fmt.Println(api.getErrorMessage())42}43func main() {44 fmt.Println(api.getErrorMessage())45}46func main() {47 fmt.Println(api.getErrorMessage())48}49func main() {50 fmt.Println(api.getErrorMessage())51}

Full Screen

Full Screen

getErrorMessage

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println(api.GetErrorMessage(404))4 fmt.Println(api.GetErrorMessage(500))5 fmt.Println(api.GetErrorMessage(200))6}

Full Screen

Full Screen

getErrorMessage

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println(err)4 fmt.Println(api.GetErrorMessage(err))5}6import (7func main() {8 fmt.Println(err)9 fmt.Println(api.GetErrorMessage(err))10}11import (12func main() {13 fmt.Println(err)14 fmt.Println(api.GetErrorMessage(err))15}16import (17func main() {18 fmt.Println(err)19 fmt.Println(api.GetErrorMessage(err))20}21import (22func main() {23 fmt.Println(err)24 fmt.Println(api.GetErrorMessage(err))25}26import (27func main() {28 fmt.Println(err)29 fmt.Println(api.GetErrorMessage(err))30}31import (32func main() {33 fmt.Println(err)34 fmt.Println(api.GetErrorMessage(err))35}36import (37func main() {

Full Screen

Full Screen

getErrorMessage

Using AI Code Generation

copy

Full Screen

1import "fmt"2import "github.com/GoTraining/Training/Day3/1/api"3func main() {4 fmt.Println(api.GetErrorMessage(404))5}6import "fmt"7func GetErrorMessage(code int) string {8 switch code {9 }10}11The package name should be the same as the directory name. The package name should be unique. If you want to use a package, you need to import it. To import a package, you need to use the import keyword. The import keyword is used in the following format:12import "<package name>"13You can also import multiple packages in a single import statement. For example, to import the fmt and math packages, you need to use the following code:14import (15The above code imports the fmt and math packages. You can also import packages with aliases. For example, to import the math package with the alias m, you need to use the following code:16import m "math"17The above code imports the math package with the alias m. You can also use the dot (.) operator to import a package. When you use the dot (.) operator to import a package, you don’t need to use the package name to access the functions and variables of the package. For example, to import the fmt package with the dot (.) operator, you need to use the following code:18import . "fmt"19The above code imports the fmt package with the dot (.) operator. Now, you can use the Println() function without using the fmt package name. For example:20Println("Hello World")21You can also use the underscore (_) operator to import a package. When you use the underscore (_) operator to import a package, you don’t need to use the package name to access the functions and variables of the package. For example, to import the fmt package with the underscore (_) operator, you need

Full Screen

Full Screen

getErrorMessage

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Go Program to use getErrorMessage method of api package")4 fmt.Println("Error Message is:", api.GetErrorMessage())5 fmt.Println("Time is:", time.Now())6}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful