Getting server response code in oracle jet web service call - rest

I am calling a REST Webservice from Oracle jet ViewModel. The server response as I expected, but how to catch the server response (If the server response is like 400,422). I tried with the following lines of code, but it doesn't seem to be working.
self.User = oj.Model.extend({
urlRoot : self.resourceUrl,
idAttribute : "userId"
});
var user = new self.User();
user.save(
{
success: function(user, response, options) {
console.log("response "+response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("error thrwos "+errorThrown);
console.log("status "+textStatus);
}
});
All I want to do is, if server response is a success, show the user a success message and navigate to the next page and if the response is an error( 400 or 422 or whatever), show the user an error message ( this can be done using a validator).

Looking at the JSDocs for model.save http://www.oracle.com/webfolder/technetwork/jet/jsdocs/oj.Model.html#save
You will see that you can define a callback function to handled the error returned by the save call.
This would work with what #Koshinae is saying in his comment above about options.

Related

How can I know the type of error and response code from IOWebSocketChannel

I am trying to know if the connection error is Connection to 'some URL' was not upgraded to websocket. Also identify response code. The server is emitting 401.
I need this to know if I need to refresh the token and then reconnect.
final channel = IOWebSocketChannel.connect(Url)
final sub = channel.stream.listen((data){
//process data
},
onError: (error){
//confirm this error failing to upgrade and
// response code is 401
// then refresh token and reconnect
})
To know the error type
print('error type is ${error.runtimeType}');
then you can handle it
if(error is errorType)
{
...
}

Angular 2 how to read Custom error message from backend

My problem with Angular 2 that was not exist in AngularJS, that I was sending the error message as a string with backend API call in case I have error, with error status 401 as example, the problem now that I can't read this message from Angular2 http response message, while I can do that from AngularJS:
I tried the following codes and nothing was helpful:
Promise:
this._http.post('/login',{email: 'email#example.com', password: '123'})
.toPromise()
.then((resp) => console.log(resp), (error) => console.log(error));
Observable:
this._http.post('/login',{email: 'email#example.com', password: '123'})
.subscribe(response =>console.log(response), (error) => console.log(error));
And from back-end I send response as a text, for OK or Unauthorized, for OK i send back String token == UUID.randomUUID().toString();, for error I send back message like String error = " Invalid credentials ";, the problem is that the console.log works and print the text for success (token in this case), but in case error, its just prints: Response with status: 200 for URL: null.
If I change code to JSON.stringify(error) I get something like this:
{"_body":{},"status":401,"ok":false,"statusText":"Unauthorized","headers":{"null":["HTTP/1.1 401 Unauthorized"],"Access-Control-Allow-Headers":["Origin"," X-Requested-With"," Content-Type"," Accept"," Referer"," User-Agent"],"Access-Control-Allow-Met
hods":["POST"," GET"," PUT"," DELETE"," OPTIONS"],"Access-Control-Allow-Origin":["*"],"Allow":["*"],"Content-Length":["36"],"Content-Type":["text/plain; charset=utf-8"],"Date":["Tue"," 23 Aug 2016 14:53:25 GMT"]},"type":2,"url":null}
As you can see the error test not even mentioned inside the Object !!
I tried to change the response for error from backend to return json like this:
{
"message": "invalid email or password"
}
I can get the result inside _body, and I can only read it like this: console.log(error._body.message) ! but i feel its something wrong this way, and I don't want to response as a json in this case.
For angularjs (angular 1), its so simple just to print the response and everything is cool, while in angular 2 its a really problem.
What the problem, and how I can solve this issue without any refactor to backend?
Edit:
I'm using Angular 2.0.0-rc.4 and same for http : `"#angular/http": "2.0.0-rc.4"
Mothanfar
In my case I'm working with the Asp Web Api as back end,this thing is making me crazy as well, the only solution I found is transform in a json and read the message, I know is really ugly but works for me.
Regards.
CheckError(error: any) {
let servermsg: any = JSON.parse(error._body)["ModelState"]["Login"][0];
if (servermsg) {
this.showMsg = true;
this.msg = servermsg;
}
}
If you are returning JSON object from the server, you may use the below code at client side:
let errMsg: ErrorMessage = err.json();
console.log(errMsg.message)
export class ErrorMessage {
message:string;
}

meteor update - collection not updating even though it reports it does

I'm trying to update a collection but I for some reason, even though it traces as having succeeded, when I view that collection in my console it doesn't appear to have updated.
Here's what I'm doing:
1) calling the update function from a javascript function on the client. All the values are being passed correctly:
Meteor.call('minisiteUpdater',vLayout,vColour,vBG,vHFont,vBFont,vFontColour);
2) the function itself (defined in Meteor.methods) is as follows. Note that when I log everything in the console, all the values are passed successfully into the function and the siteID I get from the session var is also correctly set. The problem is that the console is logging "success", which suggests to me that the update has worked, but when I enter Therapistminisite.find().fetch() into the console afterwards and look at the supposedly updated collection item, it has not been updated.
minisiteUpdater: function(vLayout,vColour,vBG,vHFont,vBFont,vFontColour){
var updates = { $set: {
layout: vLayout,
colour: vColour,
backgroundimage: vBG,
headingfont: vHFont,
bodyfont: vBFont,
fontcolour: vFontColour
}};
var siteID = Session.get("currentSiteBuilderID");
Therapistminisite.update(siteID, updates, function (error) {
if (error){
console.log(error);
}
else{
console.log("success");
}
});
},
Finally, just after I get the "success" logged in the console, I also get the following error message: "Error invoking Method 'minisiteUpdater': Internal server error [500]".
Anyone have any ideas?
If that is the method definition for both the server and the client,
you can't call Session.get on the server side, so that method succeeds when called in the browser, but then fails when called on the server. If you look in your server console, you should see a server error: Session is not defined corresponding to the 500 error in the browser console.
try adding the siteId as a method param, and removing the line that gets it from the session:
minisiteUpdater: function(vLayout,vColour,vBG,vHFont,vBFont,vFontColour, siteID){
var updates = { $set: {
layout: vLayout,
colour: vColour,
backgroundimage: vBG,
headingfont: vHFont,
bodyfont: vBFont,
fontcolour: vFontColour
}};
Therapistminisite.update(siteID, updates, function (error) {
if (error){
console.log(error);
}
else{
console.log("success");
}
});
},
(remove this line: var siteID = Session.get("currentSiteBuilderID");)
and then pass in Session.get("currentSiteBuilderID") when you call it from the client like this:
Meteor.call(
'minisiteUpdater',
vLayout,
vColour,
vBG,
vHFont,
vBFont,
vFontColour,
Session.get("currentSiteBuilderID")
);

Configuring Restivus POST method for Meteor

I have the following Restivus configuration:
if(Meteor.isServer){
Restivus.configure({
});
//Allow Restivus to manage Reports
Restivus.addCollection('reports');
Restivus.addRoute('newReport/:message', {}, {
// POST
post: {
action: function(){
var response = null;
var message = this.urlParams.message;
if(message){
console.log("Message received: " + message);
return {status: "success", data: message};
} else {
console.log("Message empty...");
return {status: "fail", message: "Post not found"};
}
//Response to caller
return;
}
}
})
}
Following the explanation of Restivus, when I make a GET call to http://localhost:3000/api/newReport/ I should get a "Get All" result from the server, on the caller.
However, if I use curl -X GET http://localhost:3000/api/newReport/ on the command line, I seem to be getting the HTML code of the site at api/NewReport/ (which is empty, except for the header and empty body)
Knowing that, I know my error is in the Restivus Route configuration, but I cannot pinpoint the reason.
The expected behavior is that when I make a POST from a Ruby script, I should get a returned message (Ok or Fail), and in my Meteor console, I should see either "Message received" or "Post not found" (both placeholders).
Additional question, is there a way to disable the default GET method Restivus creates when we add a collection?
You have to create a variable in the JavaScript part and use that in the Restivus.addCollection() call.
Reports = Mongo.Collection('reports')
if(Meteor.isServer){
Restivus.configure({
});
//Allow Restivus to manage Reports
Restivus.addCollection(Reports);
...

Restangular all("customers").getList() does not return result

I started using Restangular to send RESTful requests from my AngularJS app. I have a REST service deployed on http://localhost:20080/v1/customer which produces JSON with customer information.
When I debug AngularJS app it hits a breakpoint in the back-end REST service, however in the browser console it always logs "Failed to find customers with status code 0". Moreover, I never hit the breakpoint in the function that I register as setResponseExtractor.
I also don't see any errors in the console.
When I open http://localhost:20080/v1/customer in the browser I get the following response:
[{"customerInfo":{"name":"My Name","email":"My Email"},"id":"6ca43d0f-94a8-36e8-af3d-963584573d6d"}]
My Restangular code is as follows:
var customerModule = angular.module('customer-module',
['restangular' ]).config(
['RestangularProvider', '$httpProvider',
function (RestangularProvider, $httpProvider)
{
RestangularProvider.setBaseUrl('http://localhost\\:20080/v1');
RestangularProvider.setResponseExtractor(function (response, operation, what) {
return response;
});
...
customerModule.controller('CustomerCtrl',
[ '$scope', 'Restangular', function ($scope, Restangular)
{
var baseCustomers = Restangular.all("customer");
$scope.customers = baseCustomers.getList().then(function (result) {
console.log("Got customers", response.status);
}, function (response) {
console.log("Failed to find customers with status code", response.status);
});
Thoughts?
I'm the creator of Restangular.
You also don't have to add the responseExtractor to the config if you're just returning the response. That's what it does by default.
If you have any other problem, please contact me!
The problem turned out to be with accessing REST services running on a different port than my AngularJS app.
I am moving this thread to AngularJS mailing list - "Problems with a basic $resource.get() call"
Alec