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?

spring mvc。RestController。httpメソッドがpost またはputまたはpatch。bodyをnullにしたらエラーになった。curlでリクエストなげたら、curlコマンドでエラーになった。仕様?

Posted at

Spring MVCにおいて、@RestControllerで定義されたエンドポイントに対してPOST、PUT、PATCHメソッドを使ってリクエストを送る場合、リクエストボディがnullであるとエラーになることがあります。これは通常の動作であり、Spring MVCの仕様の一部です。

詳細

HTTPメソッドとリクエストボディ:

POST, PUT, PATCHメソッドは、リクエストボディにデータを含むことを期待しています。
リクエストボディがnullの場合、Springはデフォルトでエラーをスローする可能性があります。

エラーハンドリング:

Spring MVCでは、リクエストボディが必要な場合に@RequestBodyアノテーションを使用します。このアノテーションは、リクエストボディがnullであるとHttpMessageNotReadableExceptionをスローします。

curlコマンドの例:

正常なリクエストの例(JSONデータを含む場合):

curl -X POST http://localhost:8080/api/example -H "Content-Type: application/json" -d '{"key":"value"}'

リクエストボディをnullにするとエラーになる例:

curl -X POST http://localhost:8080/api/example -H "Content-Type: application/json" -d ''

解決策

リクエストボディが必須でない場合:

エンドポイントメソッドの引数に@RequestBody(required = false)を指定します。これにより、リクエストボディがnullでもエラーが発生しなくなります。

@PostMapping("/example")
public ResponseEntity<String> handlePost(@RequestBody(required = false) MyRequestBody body) {
    if (body == null) {
        // ボディがnullの場合の処理
        return ResponseEntity.badRequest().body("Request body is missing");
    }
    // 正常な処理
    return ResponseEntity.ok("Success");
}
```[
#### ボディが必須である場合:

リクエストボディがnullでないことを前提にしたエラーメッセージを提供することができます。
```bash
@PostMapping("/example")
public ResponseEntity<String> handlePost(@RequestBody MyRequestBody body) {
    // ここにビジネスロジックを記述
    return ResponseEntity.ok("Success");
}

エラーメッセージやレスポンスを改善することで、クライアントが何が間違っているのかを理解しやすくなります。

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?