1

According to the openCPU documentation, there are some default HTTP status codes and return types for a few situations. For example, when R raises an error, openCPU returns code 400 with a response type of text/plain.

While I believe it should be possible to control those things, is it possible to customize any of those things directly from R? For example, what if I wanted to return a JSON for a specific error in my R function, with a status code 503?

eduardokapp
  • 1,612
  • 1
  • 6
  • 28

1 Answers1

1

You can change their R package behavior by forking opencpu or via a local copy i.e. not sure if package allows this like a functionality but the responses are configured in res.R

For e.g. this method in the link above uses 400 for error.

error <- function(msg, status=400){
    setbody(msg);
    finish(status);
  }

I will update the answer if I can confirm this is available without changing package code.

UPDATE 17-04-2021

You can write your serving html i.e. index.html which uses opencpu.js to call the corresponding R functions from your app, the return type can be requested to be json in the opencpu.js call. And in the R function , you can tryCatch() errors to send appropriate error code as a json argument.

For e.g. in the stock example app you can see the file stock.js which calls the functions from R folder i.e.

//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);
    });
  }

The corresponding R code being called is in listbyindustry.R, inside which you can tryCatch() and send custom json.

  • Any updates on that? It should be possible to do it without changing source code. – eduardokapp Apr 16 '21 at 13:46
  • 1
    Its a feature request on their repo , still open, see [here](https://github.com/opencpu/opencpu/issues/111) for more details. Note that text/plain response type is only for errors generated by R. So the best bet you have is to do try catch in R and based on the results send a json object to the HTTP GET request , this way you can parse custom error codes (not really error codes but json messages/data). – Siddharth Bhatia Apr 17 '21 at 07:48