如何在 Rails 4 中返回 404 JSON 格式? [英] How can I return a 404 JSON format in Rails 4?

查看:47
本文介绍了如何在 Rails 4 中返回 404 JSON 格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Ruby 的新手.我正在使用 Rails 4 编写一个 Restful API 应用程序.找不到记录时如何返回 404 JSON not found 字符串?

I am new to Ruby. I am writing a Restful API application using Rails 4. How can I return a 404 JSON not found string when the record is not found?

我找到了很多帖子,但没有运气,仅适用于 Rails 3.

I found a number of posts but no luck, only for Rails 3.

在我的控制器中,我可以捕获异常

In my controller I can caught the exception

  def show
    country = Country.find(params[:id])
    render :json => country.to_record
  rescue Exception
    render :json => "404"
  end

但我想要一个通用的来捕获所有未找到的资源.

But I want a generic one to capture all the not found resources.

推荐答案

使用 rescue_from.请参阅http://guides.rubyonrails.org/v2.3.11/action_controller_overview.html#rescue

在这种情况下使用类似:

In this instance use something like:

class ApplicationController < ActionController::Base
  rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found

  private
  def record_not_found(error)
    render json: { error: error.message }, status: :not_found
  end
end

这篇关于如何在 Rails 4 中返回 404 JSON 格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆