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?

StringHttpMessageConverterのレスポンス書き込みのwriteメソッドでBodyがnullだと例外スローする

Posted at

📝 write() メソッドの場合(レスポンス書き込み)

@Override
protected void writeInternal(String str, HttpOutputMessage outputMessage)
        throws IOException {
    Charset charset = getContentTypeCharset(outputMessage.getHeaders().getContentType());
    OutputStream out = outputMessage.getBody();
    StreamUtils.copy(str, charset, out);
}
  • strnull の場合 → StreamUtils.copy(str, ...)NullPointerException が発生します。
  • このため、write() の前に呼び出し側が null チェックしていないと、実行時に NPE(NullPointerException) が発生します。

✅ 対策

  • @ResponseBodyHttpEntity<String> を返すような処理で null を返す可能性がある場合は、明示的に空文字列 "" を返すようにするのが安全です。
  • カスタムの HttpMessageConverter を定義して null を許容することも可能ですが、一般的には避けた方が無難です。
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?