duanming0494 2019-08-05 03:52
浏览 155

如何使用OpenAPI Generator客户端SDK访问HTTP错误正文

OpenAPI Generator creates API functions that follow the general pattern:

func (api *MyAPI) OperationId(context.Context) (ResponseStruct, *http.Response, error)

How can I retrieve the HTTP body on an error? When the HTTP Status Code is an error, error is not nil, however, it does not include the body and neither does *http.Response as the body has been read already. And, the error is not unmarshaled into the ResponseStruct as the success and failure definitions. are different.

  • 写回答

1条回答 默认 最新

  • drvpvmz16241016 2019-08-05 04:01
    关注

    The generated client creates a mypackage.GenericOpenAPIError struct which is returned as an error, where mypackage is the package name of the client. It stores the HTTP error body in the GenericOpenAPIError.body property which can be accessed by the Body() []byte function. However, because function definition returns an error which does not support the Body() function the error needs to be cast before you can access it.

    Here's the code that creates the error from a generated client:

    if localVarHttpResponse.StatusCode >= 300 {
        newErr := GenericOpenAPIError{
            body:  localVarBody,
            error: localVarHttpResponse.Status,
        }
    

    To access the body property, casting the error is needed. For example:

    data, resp, err := myclient.MyAPI.OperationId(context.Background())
    if err != nil && resp.StatusCode >= 300 {
        openAPIErr := err.(mypackage.GenericOpenAPIError)
        fmt.Println(string(openAPIErr.Body()))
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line