Angularjs http request doesn't go in errorCallback - javascript

I'm using angularjs to call my Rest web services but I have a problem with error handle.
This is one of my http calls:
$http({
method: 'POST',
url: "tr"+licenseSelected,//angular need string in url
headers: {'Content-Type': 'application/json'},
data : updatedLicense,
beforeSend: function() {
waitingModal.showPleaseWait();
},
complete: function() {
setTimeout(function(){
waitingModal.hidePleaseWait();
}, 1000);
}
}).then(function successCallback(response) {
if (response.data.success==true){
licenseTable.ajax.reload();
$('#updateLicenseModal').modal("hide");
notifyMessage(response.data.result, 'success');
} else {
notifyMessage(response.data.result, 'error');
}
}, function errorCallback(response) {
window.location.href = "/ATS/500";
});
I would like to show 500 page if an error occurred during http request (for example server down or wrong url), but errorCallback is never called.
Is there an error in my code? where is my fault?Thanks
This is an example of response that I can't handle in error code:
{
"status":422,
"exception":"org.springframework.web.method.annotation.MethodArgumentTypeMismatchException",
"message":"Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: \"tr71\"",
"stacktrace":"org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: \"tr71\"
at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:115)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:78)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:162)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:129)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:111)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:806)
......"
}
Web service example
#Override
#RequestMapping(value = { "/license"}, method = RequestMethod.POST)
public #ResponseBody Response createLicense(#RequestBody ClientLicenseForm clientLicenseForm) {
try{
administrationService.createLicense(clientLicenseForm);
return new Response(true, true, "Your license has been created!", null);
}catch(Exception e){
ErrorResponse errorResponse= ErrorResponseBuilder.buildErrorResponse(e);
LOG.error("Threw exception in AdministrationControllerImpl::createLicense :" + errorResponse.getStacktrace());
return new Response(false,false,"Error! Your license hasn't been created!",errorResponse);
}
}
This may be the problem(it wrap json response inside another object), but how can I fix it?
UPDATE
I have fixed with this code, I'll test it
}).then(function successCallback(response) {
if (typeof response.data.success == 'undefined'){
window.location.href = "/ATS/500";
}else if (response.data.success==true){
licenseTable.ajax.reload();
$('#updateLicenseModal').modal("hide");
notifyMessage(response.data.result, 'success');
} else if(response.data.success==false) {
notifyMessage(response.data.result, 'error');
}
}, function errorCallback(response) {
window.location.href = "/ATS/500";
});

Redarding you comments you get a json response (i think with 200 header)
The error callback will not fire while in the header response was 200 code.
You can manage it in two ways:
Rewrite backend side to return proper status header code
Check if response valid in successCallback
if (response.data.exception) {
window.location.href = "/ATS/500";
}
NOTE: but basically it's wrong that server return this type or error with stacktrace.
Exceptions handling examples

Related

Alert if JSON Data is Empty - Code not working

I want to check if json data is empty or not.
if json its empty, i want to alert orders Not Found.
If its not empty, i want to alert orders found.
if user not logged in, there won't be any token in his localstorage. so he will get a 500 error when browser requests the API URL. then I want to alert failed along with the failed status reason
my dev is sick, so tried my self. its not going too well.
Tried the below code, not at all working.
<script>
$http.get("http://localhost.com/activeorders/?format=json",{
headers: {'Authorization': 'Token '+ localStorage.getItem("token")}})
.success(function(response) {
if(response=="[]")
{
alert(" orders NOT found");
}
else
{
alert("orders found");
}
.error(function(response,status) {
alert("failed");
alert(status);
}
return ;
});
</script>
Any help will be thankfull.
if you are trying to do in Angular js, then you can try the code below using callbacks:
$http({
method: 'GET',
url: 'http://localhost.com/activeorders/?format=json',
headers: {
'Authorization': 'Token '+ localStorage.getItem('token')
}
}).then(function successCallback(response){ // this callback will be called asynchronously when the response is available
if (response.data.length == 0){
console.log("orders NOT found")
}
// or if you just return an array json by php for example
//if (response.length == 0) {
//console.log("orders NOT found")
//}
}, function errorCallback(response){ // called asynchronously if an error occurs or server returns response with an error status.
if (response){
alert("failed");
}
});
If you are using an external file .json type, you can try :
menuApp.controller("dynamicMenuController", function($scope, $http) {
$http.get('config/menu.json').success(function(data) {
console.log("success!");
if(data.length == 0){
alert('empty');
}
else {alert('some here!')}
});
If your json is in another domain, an external domain . In this case , I suggest you look at JSONP instead, here's an example http://fdietz.github.io/recipes-with-angular-js//consuming-external-services/consuming-jsonp-apis.html:
$http.jsonp('http://teckstack.com/api/get_recent_posts/?callback=JSON_CALLBACK').success(function (data) {
console.log("success callback");
if(data.length == 0){
alert('empty');
} // response data
}).error(function (data) {
console.log("failed callback");
});
If you want to check if a JS object or JSON is empty ({}), for example, your object is response:
Object.keys(response).length === 0 && response.constructor === Object
Try
if( Object.keys(JSON.parse(response)).length == 0 ){
alert("err")
}

AJAX error is returned as Success

AJAX error is being returned as Success. How to return JSON error from ASP.NET MVC? Could you tell me what I'm doing wrong? Thank you.
[HttpPost]
public JsonResult Register(int EventID)
{
try
{
// code
return Json(new { success = true, message = "Thank you for registering!" });
}
catch (Exception ex)
{
return Json(new { success = false, message = ex.Message });
}
}
$.ajax({
url: "#Url.Action("Register", "Home")",
type: "post",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(postData),
success: function(data) {
},
error: function (data) {
}
});
The error function gets executed only when the HTTP Response Code is not HTTP 200 Ready. You handle the error in the server-side and return proper response, which will be picked up by success function in the AJAX call. Instead, use the status variable in your JSON and handle it on the client side:
success: function(data) {
if (typeof data == "string")
data = JSON.parse(data);
if (data.success) {
// Code if success.
} else {
// Code if error.
}
},
From the docs (scroll down to the error section):
A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event.
The Ajax error method is hit only when you get a Yellow Screen Error in the server side. In your scenario you are handling the error using try catch and returning a valid response. So this is not considered as a error but a valid response. Remove your try catch so that Ajax will pick up the error event, else if you want to show the actual error message from server then you can use the success property to decide if the response was a success or a error , its similar to what Praveen has already posted in his answer.
success: function(data) {
if (data.success) { //as you are passing true/false from server side.
// Code if success.
} else {
// Code if error.
}
},

Ajax response status 200 but shows error message

I'm getting status as 200 but it's printing message present inside error message alert("error...");. Why so?
function makeSelect() {
var blouseoption = document.querySelector('input[name="blouseoption"]:checked').value;
var url = "http://dukano.co/sakhidev/retailon/productoption/values";
alert(url);
var jsondata = $j('#customoption').serialize();
alert("jsondata: " + JSON.stringify(jsondata));
$j.ajax({
type : 'POST',
url : url,
data : jsondata,
dataType : 'json',
success : function(response) {
console.log("calling");
console.log(response);
alert("call success");
alert("response data:" + JSON.stringify(response));
if (response.status == 200) {
console.log("yes");
} else if (response.status == "error") {
console.log("no");
}
},
error : function(response) {
alert("error...");
alert("response:" + JSON.stringify(response));
console.log(response);
}
});
}
Magento's controller function returning json value
public function valuesAction(){
$blouseoption = $this->getRequest()->getParam('blouseoption');
$sareefinishing = $this->getRequest()->getParam('sareefinishing');
$data = array( 'sfinishing' => $sareefinishing, 'layout' => $this->getLayout());
Mage::dispatchEvent('product_custom_option', $data);
$jsonData = json_encode(array($blouseoption, $sareefinishing));
$this->getResponse()->clearHeaders()
->setHeader('Content-type','application/json',true);
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($jsonData));
$this->getResponse()->sendResponse();
}
As you are using
dataType: "json"
this evaluates the response as JSON and returns a JavaScript object.any malformed JSON is rejected and a parse error is thrown.
This means that if server returns invalid JSON with a 200 OK status then jQuery fires the error function and set the textStatus parameter to "parsererror".
Make sure that the server returns valid JSON. empty response is also considered invalid JSON; you could return {} or null for example which validate as JSON.
try to check the textStatus in the error.
error : function(jqXHR,textStatus,errorThrown)
{console.log(textStatus)}
if this prints "parsererror" then of course you have problem with your returning json. please check that.
More Info
Alternative answer
Instead of returning status 200 with empty response, you can return status 204 and not return any response. Status 204 is for No Content. JQuery should not throw any error in this case.

No response status in ajax call not sure why

I have the following ajax call which is made to my spring mvc app..
alert("ready");
$.ajax({
type: "GET",
url: document.location.toString()+ "/dashboard",
success: function(response) {
alert(response);
alert(response.status);
$("#frameBody").contents().find("html").html(response);
// we have the response
if(response.status == "SUCCESS") {
alert(response);
// do nothing..
// check for no content... if there is content... replace iframe
// $("#frameBody").attr('src', jsonObj.url);
// $(""#frameBody").contents().find("html").html(response);
}
else {
// do nothing yet
}
},
error: function(e){
$("#errors").attr("style", "display:inline")
$('#errors').html(e.responseText);
window.setTimeout("fadeErrorsDiv();", 5000);
}
});
my mvc controller:
#RequestMapping(value = "/dashboard", method = RequestMethod.GET)
#ResponseStatus(value=HttpStatus.OK)
public String dashboard(Model model, HttpServletRequest req) {
int i = 0;
return "login";
}
My question is that i cant see why this is not producing the response status that i expect?... it gives me undefined when i check for response.status in javascript?.. any idea why
See JQuery .get docs. It would seem your "response" object inside your success callback will actually be "login". Therefore you're infact trying to do "login".status.

ASP.NET MVC HttpException message not shown on client

I'm building a RESTful web api with asp.net mvc, which returns pure json data. On my client, I'm using backbone.js to communicate to it.
My question is, how do I capture the message in javascript? For eg. What if a user has no permission to delete or there was no item matching the id? I've been told to throw http errors instead of custom json.
So my code would be:
[HttpDelete]
public ActionResult Index(int id)
{
if (id == 1)
{
throw new HttpException(404, "No user with that ID");
}
else if (id == 2)
{
throw new HttpException(401, "You have no authorization to delete this user");
}
return Json(true);
}
How do I access the message in my javascript callback? The callback would look like:
function (model, response) {
alert("failed");
//response.responseText would contain the html you would see for asp.net
}
I do not see message i threw in the exception anywhere at all in the data that was returned from the server.
You should use the error callback on the client. The success callback is triggered only when the request succeeds:
$.ajax({
url: '/home/index',
type: 'DELETE',
data: { id: 1 },
success: function (result) {
alert('success'); // result will always be true here
},
error: function (jqXHR, textStatus, errorThrown) {
var statusCode = jqXHR.status; // will equal to 404
alert(statusCode);
}
});
Now there is a caveat with 401 status code. When you throw 401 HTTP exception from the server, the forms authentication module intercepts it and automatically renders the LogIn page and replaces the 401 status code with 200. So the error handler will not be executed for this particular status code.
I just answered this in my question What is the point of HttpException in ASP.NET MVC, but you can actually get that string if you use the HttpStatusCodeResult like this:
In your controller:
return new HttpStatusCodeResult(500,"Something bad happened")
And you can access "Something bad happened" using, say, jQuery $.ajax() like this:
$.ajax: {
url: "#Url.Action("RequestsAdminAjax", "Admin")",
type: "POST",
data: function(data) { return JSON.stringify(data); },
contentType: "application/json; charset=utf-8",
error: function (xhr, textStatus,errorThrown) {
debugger;
toggleAlert('<strong>Error: </strong>Unable to load data.', 'alert alert-danger');
}
},
and errorThrown will contain "Something bad happened".
HTH.

Categories

Resources