github.com/jenspinney/cli@v6.42.1-0.20190207184520-7450c600020e+incompatible/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  			_ = json.Unmarshal(rawHTTPStatusErr.RawResponse, &routingAPIErrorBody)
    37  			if routingAPIErrorBody.Message == expiredTokenMessage {
    38  				return routererror.InvalidAuthTokenError{Message: "Token is expired"}
    39  			}
    40  			if routingAPIErrorBody.Message == unauthorizedMessage {
    41  				return routererror.UnauthorizedError{Message: routingAPIErrorBody.Message}
    42  			}
    43  		}
    44  	}
    45  
    46  	return err
    47  }
    48  
    49  func (e *ErrorWrapper) Wrap(connection router.Connection) router.Connection {
    50  	e.connection = connection
    51  	return e
    52  }