github.com/wanddynosios/cli/v8@v8.7.9-0.20240221182337-1a92e3a7017f/api/router/wrapper/error_wrapper.go (about)

     1  package wrapper
     2  
     3  import (
     4  	"encoding/json"
     5  	"net/http"
     6  
     7  	"code.cloudfoundry.org/cli/api/router"
     8  	"code.cloudfoundry.org/cli/api/router/routererror"
     9  )
    10  
    11  const expiredTokenMessage = "Token is expired"
    12  const unauthorizedMessage = "You are not authorized to perform the requested action"
    13  
    14  // ErrorWrapper is the wrapper that converts responses with 4xx and 5xx status
    15  // codes to an error.
    16  type ErrorWrapper struct {
    17  	connection router.Connection
    18  }
    19  
    20  func NewErrorWrapper() *ErrorWrapper {
    21  	return new(ErrorWrapper)
    22  }
    23  
    24  func (e *ErrorWrapper) Make(request *router.Request, passedResponse *router.Response) error {
    25  	err := e.connection.Make(request, passedResponse)
    26  
    27  	if rawHTTPStatusErr, ok := err.(routererror.RawHTTPStatusError); ok {
    28  		if rawHTTPStatusErr.StatusCode == http.StatusNotFound {
    29  			var resourceNotFoundError routererror.ResourceNotFoundError
    30  			_ = json.Unmarshal(rawHTTPStatusErr.RawResponse, &resourceNotFoundError)
    31  			return resourceNotFoundError
    32  		}
    33  
    34  		if rawHTTPStatusErr.StatusCode == http.StatusUnauthorized {
    35  			var routingAPIErrorBody routererror.ErrorResponse
    36  
    37  			_ = json.Unmarshal(rawHTTPStatusErr.RawResponse, &routingAPIErrorBody)
    38  
    39  			if routingAPIErrorBody.Message == expiredTokenMessage {
    40  				return routererror.InvalidAuthTokenError{Message: "Token is expired"}
    41  			}
    42  
    43  			if routingAPIErrorBody.Message == unauthorizedMessage {
    44  				return routererror.UnauthorizedError{Message: routingAPIErrorBody.Message}
    45  			}
    46  		}
    47  	}
    48  
    49  	return err
    50  }
    51  
    52  func (e *ErrorWrapper) Wrap(connection router.Connection) router.Connection {
    53  	e.connection = connection
    54  	return e
    55  }