Error: AbstractController::DoubleRenderError when render in Rails

When work, I’ve had bug when use 2 render error 404 and 422. 

When I go to link: http://localhost:3000/products/cloths.js. Firstly, controller will understand params {name=cloths.js} and will select in database with name=cloths.js and not found any record with that name, then the website will use function render_404.

After that, website will check 422 error because the link has .js and use function render_422. At this time, this error will appear:

AbstractController::DoubleRenderError (Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like “redirect_to(…) and return”.)

To fix error, I use this code in function render after

self.response_body = nil

It will

# Clear the previous response body to avoid a DoubleRenderError
# when redirecting or rendering another view

Example for my problem:

In function 404, which render before:

def render_404
   if request.xhr? || request.format.json?
     render json: { meta: { message: "404 not found" } }, status: :not_found, layout: false
   else
     render file: path_to_error_file(404), status: :not_found, layout: false
   end
 end

And in function 422, which render after and has error  AbstractController::DoubleRenderError

def render_422
  self.response_body = nil
  if request.xhr? || request.format.json?
    render json: { meta: { message: "422 Error" } }, status: :422_error, layout: false
  else
   render file: path_to_error_file(422), status: :422_error, layout: false, 
      content_type: 'text/html'
  end
 end