I have a big problem in jQuery.ajax call. I am calling the web service whenever click the update button. I have a separate web service class, in which consist of few methods. When I calling the web service method, I have made the error handling and log the error information in db after that I have to override the “ex” that means error object to XMLHttpRequest. Is it possible to assign the SqlException to ajax object (xhr) in VB.NET? Please help me its much more useful for me.
Yes it is possible! I try to describe it in VB.NET (mostly I use C#, but I hope I'll not made syntax errors). Let us we have a Web service
<WebMethod()> _
<ScriptMethodAttribute(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)> _
Public Function GetData(ByVal Age As Integer) As String
If Age <= 0 Then
Throw(New ArgumentException("The parameter age must be positive."))
End If
'... some code
End Function
The same code in C# look like
[WebMethod]
[ScriptMethod (UseHttpGet=true)]
public string GetData(int age)
{
if (age <= 0)
throw new ArgumentException("The parameter age must be positive.");
// some code
}
In case of negative Age input the exception ArgumentException will be thrown (all what I explain stay the same for another exception like SqlException).
Now you have a JavaScript code which use jQuery.ajax to call the service. Then you can expand the code to support the exception handling in the following way:
$.ajax({
type: "GET",
url: "MyWebService.asmx/GetData",
data: {age: -5},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, textStatus, xhr) {
// use the data
},
error: function(xhr, textStatus, ex) {
var response = xhr.responseText;
if (response.length > 11 && response.substr(0, 11) === '{"Message":' &&
response.charAt(response.length-1) === '}') {
var exInfo = JSON.parse(response);
var text = "Message=" + exInfo.Message + "\r\n" +
"Exception: " + exInfo.ExceptionType;
// + exInfo.StackTrace;
alert(text);
} else {
alert("error");
}
}
});
In case of exception be thrown, we receive information about error in JSON format. We deserialize it to the object having Message, ExceptionType and StackTrace property and then display error message like following
Message: The parameter age must be positive.
Exception: System.ArgumentException
In a real application you will probably never displayed the value of the StackTrace property. The most important information are in the Message: the text of exception and in ExceptionType: the name of exception (like System.ArgumentException or System.Data.SqlClient.SqlException).
Related
I need a test case that verifies that a '400 Bad Request' is returned when an API call is made without the required field. (Previously there was a bug where the field was needed, but requests without were being accepted)
It's a simple POST call with auth and a raw body. It returns a 200 when the missing field is returned.
The POST returns the '400 Bad Request' correctly, but I can't get the test to pass.
The following tests all fail:
pm.test("Status is an error", function () {
pm.response.to.be.error;
});
pm.test("Status code is 400", function () {
pm.response.to.have.status(400);
});
The response body is:
Instantiation of [simple type, class com.[company].[product].notifications.api.v2.models.NotificationCreateV2] value failed for JSON property content due to missing (therefore NULL) value for creator parameter content which is a non-nullable type
at [Source: (byte[])"{
"field1": "string",
"field2": "Snort",
"field3": "Signature 5102",
"field4": "2019-04-19T10:34:03Z",
"field5": 0,
"field6": 4
}"; line: 8, column: 1] (through reference chain: com.[company].[product].notifications.api.v2.models.NotificationCreateV2["content"])
There is a way where you can explicitly make some tests to Pass or Fail.
Refer following code snippet this might help you.
pass=true;
fail=false;
try{
if(responseCode.code === 200)
{
var jsonData = pm.response.json();
tests["Request with 200 status ok : "+ responseCode.code] = responseCode.code === 200 === fail;
}else if(responseCode.code !== 200){
console.error("Web-service failed");
tests["Request with 400 Bad Request: "+ responseCode.code] = responseCode.code === 400;
}
}catch(err){
console.log("Something went wrong please contact to your Admin...!"+err);
}
I've deployed my ember-cli app in stage environment to let teammates test the app. In the app I have implemented Ember.onerror to email me errors that occur in stage and in production environment.
Ember.onerror = function(data) {
Ember.$.ajax({
type: "POST",
url: url + "/error",
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({message: data.message, stacktrace: data.stack}),
beforeSend: function (xhr, settings) {
xhr.setRequestHeader('Accept', settings.accepts.json);
}
});
}
I'm having difficulties in analyze stacktrace because it references only vendor.js and I can't understand where the problem really is.
For example I've received following message:
Message: Nothing handled the action 'back'. If you did handle the action, this error can be caused by returning true from an action handler in a controller, causing the action to bubble.
and stacktrace:
EmberError#http://example.com/assets/vendor-952b195e45ab9682c02f1fabba312c19.js:25705:26
triggerEvent#http://example.com/assets/vendor-952b195e45ab9682c02f1fabba312c19.js:38985:44
trigger#http://example.com/assets/vendor-952b195e45ab9682c02f1fabba312c19.js:64971:26
trigger#http://example.com/assets/vendor-952b195e45ab9682c02f1fabba312c19.js:63740:21
send#http://example.com/assets/vendor-952b195e45ab9682c02f1fabba312c19.js:38468:45
send#http://example.com/assets/vendor-952b195e45ab9682c02f1fabba312c19.js:42710:26
runRegisteredAction#http://example.com/assets/vendor-952b195e45ab9682c02f1fabba312c19.js:33277:30
run#http://example.com/assets/vendor-952b195e45ab9682c02f1fabba312c19.js:10765:30
run#http://example.com/assets/vendor-952b195e45ab9682c02f1fabba312c19.js:30030:32
handler#http://example.com/assets/vendor-952b195e45ab9682c02f1fabba312c19.js:33269:39
http://example.com/assets/vendor-952b195e45ab9682c02f1fabba312c19.js:55210:34
dispatch#http://example.com/assets/vendor-952b195e45ab9682c02f1fabba312c19.js:4872:14
handle#http://example.com/assets/vendor-952b195e45ab9682c02f1fabba312c19.js:4540:33
The meaning of the error message is clear, but I'm wondering if there's a way to easily recognize where that back action is not handled.
I have created a Datasnap REST server.
A ReverseString method gets created by default that simply reverses the string passed to the method.
When I invoke the method using the browser URL:
http://dummydomain.com:81/datasnap/rest/TServerMethods1/ReverseString/ABC
I receive {"result":["CBA"]} as result. (server runs on port 81 and the parameter passed to the method is ABC)
I have tried the following code to get the result into a variable in javascript, but without success:
var options={
type: "GET",
url: "http://dummydomain.com:81/datasnap/rest/TServerMethods1/SayHello",
data: "ABC",
dataType: "json",
success: function(data) {
var json = JSON.stringify(data);
$("p").after('<div id="data1">Your result is: ' + json.result + '</div>');
}
}
$.ajax(options);
What am I doing wrong? In the end I need 'CBA' in a variable. If there are some good resources out there, please advise. I have been googling but everybody seem to do it in their own way.
What is the best way to handle 403 errors from ember-data?
I want to know the best way to handle non validation errors, for example I have a bit of code that might return an http 403 if the user is not allowed to perform the action. For example, I have the following code:
contact.set 'something', 'something'
transaction = #get('store').transaction()
transaction.add(contact)
contact.one 'becameInvalid', (result) =>
#display some error message
contact.one 'becameError', (result) =>
# code does not get here for some reason
transaction.rollback()
#display some error message
transaction.commit()
If a 403 error happens then the above becameError handler does not get invoked and the object's state machine is left in the rootState.error state and any subsequent attempts to set a property on the object will fail because of the now infamous and dreaded:
uncaught Error: Attempted to handle event `willSetProperty` on <Radium.Contact:ember2286:17> while in state rootState.error. Called with {reference: [object Object], store: <Radium.Store:ember3219>, name: name}
My thinking is that I can override the didError method:
didError: function(store, type, record, xhr) {
if (xhr.status === 422) {
var json = JSON.parse(xhr.responseText),
serializer = get(this, 'serializer'),
errors = serializer.extractValidationErrors(type, json);
store.recordWasInvalid(record, errors);
} else {
this._super.apply(this, arguments);
}
},
My question is how do I get an object back into a usable state after the state machine has transitioned to rootState.error.
I started playing a bit with Sencha Touch.
So I've built a really simple application based on one of the examples just to see how it goes.
Basically it creates a JSON Request which executes a Last.FM web service to get music events near the user's location.
Here's the JSON code:
var makeJSONPRequest = function() {
Ext.util.JSONP.request({
url: 'http://ws.audioscrobbler.com/2.0/',
params: {
method: 'geo.getEvents',
location: 'São+Paulo+-+SP',
format: 'json',
callback: 'callback',
api_key: 'b25b959554ed76058ac220b7b2e0a026'
},
callback: function(result) {
var events = result.data.events;
if (events) {
var html = tpl.applyTemplate(events);
Ext.getCmp('content').update(html);
}
else {
alert('There was an error retrieving the events.');
}
Ext.getCmp('status').setTitle('Events in Sao Paulo, SP');
}
})
};
But every time I try to run it, I get the following exception:
Uncaught SyntaxError: Unexpected token :
Anyone has a clue?
A couple of things. First of all the "Uncaught SyntaxError: Unexpected token :" means the browser javascript engine is complaining about a colon ":" that has been put in the wrong place.
The problem will most likely be in the returned JSON. Since whatever the server returns will be run though the eval("{JSON HTTP RESULT}") function in javascript, the most likely thing is that your problem is in there somewhere.
I've put your code on a little sencha test harness and found a couple of problems with it.
First: My browser was not too happy with the "squiggly ã" in location: 'São+Paulo+-+SP', so I had to change this to location: 'Sao+Paulo,+Brazil', which worked and returned the correct results from the audioscribbler API.
Second: I notice you added a callback: 'callback', line to your request parameters, which changes the nature of the HTTP result and returns the JSON as follows:
callback({ // a function call "callback(" gets added here
"events":{
"event":[
{
"id":"1713341",
"title":"Skank",
"artists":{
"artist":"Skank",
"headliner":"Skank"
},
// blah blah more stuff
"#attr":{
"location":"Sao Paulo, Brazil",
"page":"1",
"totalpages":"1",
"total":"2"
}
}
}) // the object gets wrapped with extra parenthesis here
Instead of doing that I think you should be using the callbackKey: 'callback' that comes with the example in http://dev.sencha.com/deploy/touch/examples/ajax/index.js.
Something like this for example:
Ext.util.JSONP.request({
url: 'http://ws.audioscrobbler.com/2.0/',
params: {
method: 'geo.getEvents',
location: 'Sao+Paulo,+Brazil',
format: 'json',
api_key: 'b25b959554ed76058ac220b7b2e0a026'
},
callbackKey: 'callback',
callback: function(result) {
// Output result to console (Firebug/Chrome/Safari)
console.log(result);
// Handle error logic
if (result.error) {
alert(result.error)
return;
}
// Continue your code
var events = result.data.events;
// ...
}
});
That worked for me so hopefully it'll work for you too. Cherio.