1
0

More than 3 years have passed since last update.

go-swaggerでエラーレスポンスをハンドルする

Posted at

背景

swaggerに次のようなエラーレスポンスを追加したときに、クライアント側でどのようにハンドルして取り出すのか少し迷った。

...
    responses:
      "500":
        schema: "#/definitions/Error"
        headers:
          X-Hogefuga:
            type: string
...

クライアントでのハンドリング

swagger generate clientで生成されるコードにエラーレスポンスの型情報があるので、型アサーションしてあげると取れる。例えば500だと[...]InternalServerErrorがそれにあたる。

rep, err := api.Application.Get(params)
if reterr, ok := err.(*application.GetInternalServerError); ok {
  return fmt.Erorf("internal server error: %v[%s]", err, reterr.XHogefuga)
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0