render処理でTemplate is missingエラー


環境

Ruby:2.5.1
Rails:5.2.3

エラー内容

Railsを使用したアプリで、指定したURIに対するページがなければ404エラー用のページを表示する処理をrenderメソッドで実装していました。
以下のように存在しないファイルを指定したところ、Template is missingエラーが発生しました。
http://localhost/notexist.xml

実装内容

存在しないページが指定されるとrender_404が実行されます。

class ApplicationController < ActionController::Base

  # 例外処理
  rescue_from ActiveRecord::RecordNotFound, with: :render_404
  rescue_from ActionController::RoutingError, with: :render_404

  def render_404
    render template: 'errors/error_404', status: 404, layout: 'application', content_type: 'text/html'
  end

エラー原因

表示したいファイルの拡張子がhtmlであるのに対し、renderメソッドの:formatsオプションにURIで指定したxml拡張子が設定されていたためでした。
:formatsオプションはデフォルトではhtmlが指定されますが、指定したURIに拡張子があると:formatsオプションに設定されます。

参考:https://railsguides.jp/layouts_and_rendering.html#formats%E3%82%AA%E3%83%97%E3%82%B7%E3%83%A7%E3%83%B3

解決方法

renderメソッドの:formatsオプションを正しく指定します。
表示したいファイルは error_404.html.erb なので、formats: :htmlを指定します。

  def render_404
    render template: 'errors/error_404', status: 404, layout: 'application', content_type: 'text/html', formats: :html
  end