0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

curl の --fail-with-body オプションを使うことで、400以上のステータスのとき、異常終了して、さらにResponseBodyを出力することができる。

Posted at

目的

--fail-with-bodyを知る。

結論

  • curl を使うとき、--failもしくは--fail-with-bodyオプションをつけないと、400以上のステータスでも、正常終了してしまう。
  • --fail オプションを使うことで、400以上のステータスのとき、異常終了することができる。しかし、Response Body は出力されない。
  • --fail-with-bodyオプションを使うことで、400以上のステータスのとき、異常終了して、さらに、Response Body は出力することができる。

検証

bbb_1.sh
#!/bin/bash

set -euo pipefail

curl --fail -w "%{http_code}" -X GET \
     "https://jsonplaceholder.typicode.com/todos/123456789"

echo "Done"
bbb_2.sh
#!/bin/bash

set -euo pipefail

curl --fail-with-body -w "%{http_code}" -X GET \
     "https://jsonplaceholder.typicode.com/todos/123456789"

echo "Done"
bbb_3.sh
#!/bin/bash

set -euo pipefail

curl -w "%{http_code}" -X GET \
     "https://jsonplaceholder.typicode.com/todos/123456789"

echo "Done"
ccc.sh
#!/bin/bash

set -euo pipefail

curl -w "%{http_code}" -X GET \
     "https://jsonplaceholder.typicode.com/todos/3"

echo "Done"
# curl で異常終了しているが、Response Body({})は表示されない。
$ ./bbb_1.sh
curl: (22) The requested URL returned error: 404
404$

# curl で異常終了して、Response Body({})は表示される。
$ ./bbb_2.sh
curl: (22) The requested URL returned error: 404
{}404$ 

# curl で正常終了している。
$ ./bbb_3.sh
{}404Done

# curl で正常終了している。
$ ./ccc.sh
{
  "userId": 1,
  "id": 3,
  "title": "fugiat veniam minus",
  "completed": false
}200Done

参考

0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?