summaryrefslogtreecommitdiff
path: root/app/controllers/concerns/invalid_utf8_error_handler.rb
blob: a7ea0d00a435a5bb93b29ba68157f906d77d5456 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
module InvalidUTF8ErrorHandler
  extend ActiveSupport::Concern

  included do
    rescue_from ArgumentError, with: :handle_invalid_utf8
  end

  private

  def handle_invalid_utf8(error)
    if error.message == "invalid byte sequence in UTF-8"
      render_412
    else
      raise(error)
    end
  end

  def render_412
    respond_to do |format|
      format.html { render "errors/precondition_failed", layout: "errors", status: 412 }
      format.js { render json: { error: 'Invalid UTF-8' }, status: :precondition_failed, content_type: 'application/json' }
      format.any { head :precondition_failed }
    end
  end
end