简体   繁体   English

如何在Rails中为API定义自定义错误代码

[英]How to define custom error codes for api in rails

I want to define custom error codes in my api response like 我想在我的api响应中定义自定义错误代码,例如

{ status: 401,message: "Authentication issue",code: 1000}

I want to define this 1000 code in my app with some documentation of explanation. 我想在我的应用程序中定义1000条代码,并附上一些解释性文档。 How can I do that? 我怎样才能做到这一点?

First you need to define your custom exception: 首先,您需要定义自定义异常:

class API::Unauthorized < StandardError
  attr_reader :code

  def initialize(code)
    super
    @code = code
  end
end

Then in your APIController, use rescue_from , so add the following: 然后在您的APIController中,使用rescue_from ,因此添加以下内容:

rescue_from StandardError, :with => :exception_handler

def exception_handler(exception)
  if exception.is_a? API::Unauthorized
    render json: { status: 401, message: "Authentication issue", code: exception.code }, status: unauthorized
  end
end

Now you can throw different exception codes based on your implementation by: 现在,您可以通过以下方式根据您的实现抛出不同的异常代码:

raise API::Unauthorized.new(1000)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM