高木のブログ

【Sinatra】404 Not Found のエラーハンドリング

2022/06/10

存在しないパスにアクセスが来た時の対応

not_found ハンドラが用意されているので、これを使ったら良い

app.rb
not_found do
  json(message: '404 Not Found.')
end
$ curl localhost:4567/foo
{"message":"404 Not Found."}

ステータスコードもちゃんと 404 になっている

$ curl localhost:4567/foo -v
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 4567 (#0)
> GET /foo HTTP/1.1
> Host: localhost:4567
> User-Agent: curl/7.64.1
> Accept: */*
>
< HTTP/1.1 404 Not Found
< X-Cascade: pass
< Content-Type: application/json
< X-Content-Type-Options: nosniff
< Content-Length: 28
<
* Connection #0 to host localhost left intact
{"message":"404 Not Found."}* Closing connection 0

SNS でシェアする


ytkg

Written by ytkg, Twitter, GitHub