You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails 6 如何为自定义API异常添加API返回的错误描述信息

实现方案

你可以通过以下修改实现将API返回的错误描述附加到异常中:


基础版(仅追加错误消息)

只需要调整Client类中的handle_response方法,提取错误描述后在抛出异常时传入即可:

class Client
  include ::Errors
  
  def get(path, options = {})
    handle_response(client.public_send(:get, path.to_s, options))
  end
  
  private
  
  (...)
  
  def handle_response(response)
    return response_body(response) if response.success?
    
    # 用dig方法安全提取错误描述,避免字段不存在时报错,兜底返回通用提示
    error_msg = response.body&.dig('FirebirdApiError', 'ApiStatusDescription') || "API请求失败,状态码:#{response.status}"
    # 抛出异常时传入错误信息
    raise error_class(response.status), error_msg
  end
  
  def response_body(response)
    return if response.body.blank?
    
    response.body
  end
end

修改完成后,捕获异常时调用e.message即可直接获取API返回的错误描述。


进阶版(额外存储完整响应方便调试)

如果需要后续排查问题时能拿到完整的响应内容,可以升级异常基类,增加响应对象存储能力:

第一步:修改Errors模块的基类定义

module Errors
  class APIExceptionError < StandardError
    # 新增响应对象属性,支持后续获取完整返回内容
    attr_accessor :response

    def initialize(message = nil, response = nil)
      super(message)
      @response = response
    end
  end

  BadRequestError = Class.new(APIExceptionError)
  UnauthorizedError = Class.new(APIExceptionError)
  ForbiddenError = Class.new(APIExceptionError)
  ApiRequestsQuotaReachedError = Class.new(APIExceptionError)
  NotFoundError = Class.new(APIExceptionError)
  UnprocessableEntityError = Class.new(APIExceptionError)
  ApiError = Class.new(APIExceptionError)

  def error_class(status)
    case status
    when 400
      BadRequestError
    when 401
      UnauthorizedError
    when 403
      ForbiddenError
    when 404
      NotFoundError
    when 429
      UnprocessableEntityError
    else
      ApiError
    end
  end
end

第二步:调整handle_response抛出逻辑

def handle_response(response)
  return response_body(response) if response.success?
  
  error_msg = response.body&.dig('FirebirdApiError', 'ApiStatusDescription') || "API请求失败,状态码:#{response.status}"
  # 初始化异常时传入错误消息和完整响应对象
  raise error_class(response.status).new(error_msg, response)
end

升级后除了e.message获取错误描述外,还可以通过e.response拿到完整的响应对象,方便复杂场景下的问题排查。


内容的提问来源于stack exchange,提问作者mr_muscle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 19:15:01