【发布时间】:2021-04-07 17:21:13
【问题描述】:
根据the openCPU documentation,有一些默认的HTTP状态代码和返回类型用于少数情况。例如,当 R 引发错误时,openCPU 返回代码 400,响应类型为 text/plain。
虽然我认为应该可以控制这些东西,但是否可以直接从 R 自定义这些东西?例如,如果我想为我的 R 函数中的特定错误返回 JSON,状态码为 503,该怎么办?
【问题讨论】:
根据the openCPU documentation,有一些默认的HTTP状态代码和返回类型用于少数情况。例如,当 R 引发错误时,openCPU 返回代码 400,响应类型为 text/plain。
虽然我认为应该可以控制这些东西,但是否可以直接从 R 自定义这些东西?例如,如果我想为我的 R 函数中的特定错误返回 JSON,状态码为 503,该怎么办?
【问题讨论】:
您可以通过分叉 opencpu 或通过本地副本更改其 R 包行为,即不确定包是否允许此功能,但响应已在 res.R 中配置
例如上面链接中的这个方法使用400 表示错误。
error <- function(msg, status=400){
setbody(msg);
finish(status);
}
如果我可以在不更改包代码的情况下确认这是可用的,我将更新答案。
您可以编写您的服务 html,即 index.html,它使用 opencpu.js 从您的应用程序中调用相应的 R 函数,可以在 opencpu.js 调用中请求返回类型为 json。而在 R 函数中,您可以通过tryCatch()errors 发送适当的错误代码作为 json 参数。
例如在stock example app 中,您可以看到文件stock.js 调用R 文件夹中的函数,即
//this function gets a list of stocks to populate the tree panel
function loadtree(){
var req = ocpu.rpc("listbyindustry", {}, function(data){
Ext.getCmp("tree-panel").getStore().setProxy({
type : "memory",
data : data,
reader : {
type: "json"
}
});
Ext.getCmp("tree-panel").getStore().load();
}).fail(function(){
alert("Failed to load stocks: " + req.responseText);
});
}
被调用的对应R代码在listbyindustry.R,在里面可以tryCatch()发送自定义json。
【讨论】: