我正在构建一个应用程序,它被构建为一个 Rails 服务器应用程序,为客户端提供 RESTful api。 Rails 服务器使用 RABL。客户端是一个 Angular JS 客户端,执行标准的 $http 调用(gets、puts 等)。
有时,我的 Rails 服务器会产生错误(假设附加到对象的验证错误)或什至没有错误,在这种情况下,我想向用户显示某些内容 - 要么是错误,例如“记录没有保存,因为...... "或 "记录已成功更新"。
我正在尝试在 Rails 端和 Angular/客户端都绘制一个模式来处理这个问题。
至于 rails :
至于 Angular :
我想我希望我不必在这里重新发明轮子,有人可以向我指出当前使用和建议(和本地化)的模式。
最佳答案
我继续执行我认为需要做的事情。感谢 digger69对此有一些帮助。
在 Rails 方面,我使用了 http 状态代码。根据 here我同意使用 400 http 状态代码进行错误验证。
在我的 Controller 中,我现在有如下内容:
def create
my_obj = MyObj.build_with_params(params)
if my_obj.save
respond_with(my_obj) # regular RABL response
else
respond_with_errors(my_obj.errors)
end
end
在我的 application_controller.rb 中,我定义了一个通用方法 respond_with_errors
# respond back to the client an http 400 status plus the errors array
def respond_with_errors(errors)
render :json => {:errors => errors}, :status => :bad_request
end
请注意,已根据 here 为 Rails 定义了 :bad_request 符号。
在客户端,我需要拦截 http 调用(不仅用于验证,还用于身份验证失败(可能还有更多)。这是我在 Angular 中的代码示例(感谢 this post 对此的帮助):
var interceptor = ['$rootScope', '$q', function (scope, $q) {
function success(response) {
return response;
}
function error(response) {
var status = response.status;
if (status == 401) { // unauthorized - redirect to login again
window.location = "/";
} else if (status == 400) { // validation error display errors
alert(JSON.stringify(response.data.errors)); // here really we need to format this but just showing as alert.
} else {
// otherwise reject other status codes
return $q.reject(response);
}
}
return function (promise) {
return promise.then(success, error);
}
}];
$httpProvider.responseInterceptors.push(interceptor);
我现在可以与我的 rails 代码保持一致,并处理客户端上 http 调用的成功返回。我确定我还有一些事情要做,但我认为这提供了一个本地化的解决方案。
关于ruby-on-rails - 从 Rails 的 JSON 响应中寻找用于在 Angular 中进行通用错误处理的范例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15935814/