使用fetch()将自定义错误通过Rails后端传递到JavaScript前端可以通过以下步骤实现:
StandardError
,并在其中添加自定义的错误信息和其他属性。例如:class CustomError < StandardError
attr_reader :code, :message
def initialize(code, message)
@code = code
@message = message
end
end
在Rails的控制器或其他逻辑中,当需要抛出自定义错误时,可以使用raise
关键字抛出自定义错误对象。例如:
def some_action
# ...
raise CustomError.new(500, "Something went wrong.")
# ...
end
rescue_from
方法捕获自定义错误,并返回相应的错误信息。例如:class SomeController < ApplicationController
rescue_from CustomError, with: :handle_custom_error
def some_action
# ...
raise CustomError.new(500, "Something went wrong.")
# ...
end
private
def handle_custom_error(error)
render json: { error: { code: error.code, message: error.message } }, status: :internal_server_error
end
end
在上述代码中,rescue_from
方法用于捕获CustomError
类型的错误,并调用handle_custom_error
方法进行处理。handle_custom_error
方法将错误信息以JSON格式返回给前端,并设置HTTP状态码为500。
fetch('/some_endpoint')
.then(response => {
if (!response.ok) {
throw new Error(response.statusText);
}
return response.json();
})
.then(data => {
// 处理成功返回的数据
})
.catch(error => {
// 处理错误信息
console.error(error);
});
在上述代码中,fetch()方法发送请求到后端的某个接口。如果返回的响应状态码不是200(即请求失败),则抛出一个Error对象,并将错误信息作为Error对象的描述。在catch块中,可以处理捕获到的错误信息,例如打印到控制台或显示给用户。
通过以上步骤,可以使用fetch()将自定义错误通过Rails后端传递到JavaScript前端,并进行相应的处理。
领取专属 10元无门槛券
手把手带您无忧上云