1
0
mirror of https://github.com/mainflux/mainflux.git synced 2025-05-09 19:29:29 +08:00
Aryan Godara e6e9d22133
MF-1670 - Improve error handling in SDK (#1674)
* initial commit

Signed-off-by: aryan <aryangodara03@gmail.com>

* remove unused variables.

Signed-off-by: aryan <aryangodara03@gmail.com>

* removed temporarily created file.

Signed-off-by: aryan <aryangodara03@gmail.com>

* Fix failing CI

Signed-off-by: aryan <aryangodara03@gmail.com>

* Fix thing_test failing cases.

Signed-off-by: aryan <aryangodara03@gmail.com>

* Remove dead code, debug statements, and add comments.

Signed-off-by: aryan <aryangodara03@gmail.com>

* Extract errors to separate file.

Signed-off-by: aryan <aryangodara03@gmail.com>

* Updated things/api/http tests

Signed-off-by: aryan <aryangodara03@gmail.com>

* Created custom SDK error.

Signed-off-by: aryan <aryangodara03@gmail.com>

* Changed to using CheckError. All tests passing.

Signed-off-by: aryan <aryangodara03@gmail.com>

* Replace error interface with errors.SDKError interface.

Signed-off-by: aryan <aryangodara03@gmail.com>

* Fix failing CI.

Signed-off-by: aryan <aryangodara03@gmail.com>

* Remove unused sdk errors.

Signed-off-by: aryan <aryangodara03@gmail.com>

* Change SDKError to error in internal function of sdk package.

Signed-off-by: aryan <aryangodara03@gmail.com>

* Remove unused error.

Signed-off-by: aryan <aryangodara03@gmail.com>

* Remove encodeError. All tests working.

Signed-off-by: aryan <aryangodara03@gmail.com>

* Rename sdkerr vars, convert common strings to constants.

Signed-off-by: aryan <aryangodara03@gmail.com>

* Change checkerror to take error instead of string.

Signed-off-by: aryan <aryangodara03@gmail.com>

* Remove unused errors, and removed errfailedwhitelist wrap.

Signed-off-by: aryan <aryangodara03@gmail.com>

* Removed unused errors, and remove errors.go since it only had a repeated error from errors package

Signed-off-by: aryan <aryangodara03@gmail.com>

* Remove unused errors.

Signed-off-by: aryan <aryangodara03@gmail.com>

* Update sdk_error.

Signed-off-by: aryan <aryangodara03@gmail.com>

* Used function to reduce code for sending and receiving requests.

Signed-off-by: aryan <aryangodara03@gmail.com>

* Added function sendrequestandgetheadersorerror.

Signed-off-by: aryan <aryangodara03@gmail.com>

* sdk_error updated.

Signed-off-by: aryan <aryangodara03@gmail.com>

* Updated function names to processRequest.

Signed-off-by: aryan <aryangodara03@gmail.com>

* Made errors internal, fixed typo in http.

Signed-off-by: aryan <aryangodara03@gmail.com>

* Remove empty line.

Signed-off-by: aryan <aryangodara03@gmail.com>

* merged proceessBody and processHeaders functions in sdk.

Signed-off-by: aryan <aryangodara03@gmail.com>

* remove sendThingRequest function.

Signed-off-by: aryan <aryangodara03@gmail.com>

* changed processRequest signature

Signed-off-by: aryan <aryangodara03@gmail.com>

* changed processRequest signature, changed error names.

Signed-off-by: aryan <aryangodara03@gmail.com>

Signed-off-by: aryan <aryangodara03@gmail.com>
Co-authored-by: Dušan Borovčanin <dusan.borovcanin@mainflux.com>
2022-12-15 16:24:19 +01:00

142 lines
3.9 KiB
Go

// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package http
import (
"context"
"encoding/json"
"net/http"
"strings"
kitot "github.com/go-kit/kit/tracing/opentracing"
kithttp "github.com/go-kit/kit/transport/http"
"github.com/go-zoo/bone"
"github.com/mainflux/mainflux"
"github.com/mainflux/mainflux/internal/apiutil"
"github.com/mainflux/mainflux/logger"
"github.com/mainflux/mainflux/pkg/errors"
"github.com/mainflux/mainflux/things"
opentracing "github.com/opentracing/opentracing-go"
)
const contentType = "application/json"
// MakeHandler returns a HTTP handler for auth API endpoints.
func MakeHandler(tracer opentracing.Tracer, svc things.Service, logger logger.Logger) http.Handler {
opts := []kithttp.ServerOption{
kithttp.ServerErrorEncoder(apiutil.LoggingErrorEncoder(logger, encodeError)),
}
r := bone.New()
r.Post("/identify", kithttp.NewServer(
kitot.TraceServer(tracer, "identify")(identifyEndpoint(svc)),
decodeIdentify,
encodeResponse,
opts...,
))
r.Post("/identify/channels/:chanId/access-by-key", kithttp.NewServer(
kitot.TraceServer(tracer, "can_access_by_key")(canAccessByKeyEndpoint(svc)),
decodeCanAccessByKey,
encodeResponse,
opts...,
))
r.Post("/identify/channels/:chanId/access-by-id", kithttp.NewServer(
kitot.TraceServer(tracer, "can_access_by_id")(canAccessByIDEndpoint(svc)),
decodeCanAccessByID,
encodeResponse,
opts...,
))
return r
}
func decodeIdentify(_ context.Context, r *http.Request) (interface{}, error) {
if !strings.Contains(r.Header.Get("Content-Type"), contentType) {
return nil, errors.ErrUnsupportedContentType
}
req := identifyReq{}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
return nil, errors.Wrap(errors.ErrMalformedEntity, err)
}
return req, nil
}
func decodeCanAccessByKey(_ context.Context, r *http.Request) (interface{}, error) {
if !strings.Contains(r.Header.Get("Content-Type"), contentType) {
return nil, errors.ErrUnsupportedContentType
}
req := canAccessByKeyReq{
chanID: bone.GetValue(r, "chanId"),
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
return nil, errors.Wrap(errors.ErrMalformedEntity, err)
}
return req, nil
}
func decodeCanAccessByID(_ context.Context, r *http.Request) (interface{}, error) {
if !strings.Contains(r.Header.Get("Content-Type"), contentType) {
return nil, errors.ErrUnsupportedContentType
}
req := canAccessByIDReq{
chanID: bone.GetValue(r, "chanId"),
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
return nil, errors.Wrap(errors.ErrMalformedEntity, err)
}
return req, nil
}
func encodeResponse(_ context.Context, w http.ResponseWriter, response interface{}) error {
if ar, ok := response.(mainflux.Response); ok {
for k, v := range ar.Headers() {
w.Header().Set(k, v)
}
w.Header().Set("Content-Type", contentType)
w.WriteHeader(ar.Code())
if ar.Empty() {
return nil
}
}
return json.NewEncoder(w).Encode(response)
}
func encodeError(_ context.Context, err error, w http.ResponseWriter) {
switch {
case errors.Contains(err, apiutil.ErrBearerToken),
errors.Contains(err, apiutil.ErrBearerKey),
errors.Contains(err, errors.ErrAuthentication):
w.WriteHeader(http.StatusUnauthorized)
case errors.Contains(err, errors.ErrNotFound):
w.WriteHeader(http.StatusNotFound)
case errors.Contains(err, errors.ErrAuthorization):
w.WriteHeader(http.StatusForbidden)
case errors.Contains(err, errors.ErrUnsupportedContentType):
w.WriteHeader(http.StatusUnsupportedMediaType)
case errors.Contains(err, errors.ErrMalformedEntity),
errors.Contains(err, apiutil.ErrMissingID):
w.WriteHeader(http.StatusBadRequest)
default:
w.WriteHeader(http.StatusInternalServerError)
}
if errorVal, ok := err.(errors.Error); ok {
w.Header().Set("Content-Type", contentType)
if err := json.NewEncoder(w).Encode(apiutil.ErrorRes{Err: errorVal.Msg()}); err != nil {
w.WriteHeader(http.StatusInternalServerError)
}
}
}