当找不到资源而不是HTML时如何返回404

我有这个控制器:

completeRequestReturningItems([],completionHandler:)

我想知道如何返回# frozen_string_literal: true class MetricsController < ApplicationController before_action :set_post,only: [:update] def update if @post.update(post_params) render json: @post else render json: @post.errors,status: :unprocessable_entity end end private def set_post @post = Post.find_by(site: params[:site_id],post_id: params[:post_id]) end def post_params params.fetch(:post,{}) end end 404时找不到的@post。现在,如果nil@post.update,并且响应为HTML,则@post会引发错误。

qsylhh 回答:当找不到资源而不是HTML时如何返回404

当找不到记录时,可以利用ActiveRecord::FinderMethods#find_by!引发ActiveRecord::RecordNotFound而不是nil的情况,然后使用rescue_from块来处理错误

class MetricsController < ApplicationController
  rescue_from ActiveRecord::RecordNotFound do |exception|
    # it is up to you create RecordNotFoundSerializer
    serializer = RecordNotFoundSerializer.new exception

    render json: serializer.to_json,status: :not_found
  end

  private

  def set_post
    @post = Post.find_by(site: params[:site_id],post_id: params[:post_id])
  end
end

您还可以将错误处理提取到基本控制器(在您的示例中为ApplicationController)并在那里集中错误处理。

,

如果@post为零,则可以添加检查并返回not_found,以防止您的应用崩溃,您可以通过添加rescue块并从那里返回所需的错误来处理其他错误

def update
 return render json: YOUR_ERROR,status: :not_found unless @post
 if @post.update(post_params)
   render json: @post
 else
   render json: @post.errors,status: :unprocessable_entity
 end
rescue StandardError => e
  render json: e,status: :unprocessable_entity
end
,

您可以将@post的支票添加到控制器操作中,如果是nil,则返回404:

def update
  if @post
    if @post.update(post_params)
      render json: @post
    else
      render json: @post.errors,status: :unprocessable_entity
    end
  else
    render json: YourCustomJsonError,status: 404
  end
end
本文链接:https://www.f2er.com/3150215.html

大家都在问