Does anyone know how to handle exception sent from server? It might be unauthorized exception or no response from server as well.
var query = breeze.EntityQuery.from("Partners");
manager.executeQuery(query, function (data) {
............
}
Data is being fetched using the code very well. I just want to add a exception handler.
Try this... In the function failed it throws the exception message
var query = breeze.EntityQuery.from("Partners");
manager.executeQuery(query).then(success).fail(failed)
function success(data){
}
function failed(error){
}
Related
This code works:
firebase.database().ref($scope.language).orderByChild('word').equalTo($scope.word).once('value')
.then(function(snapshot) {
console.log(snapshot.val());
})
It logs the object and its key.
This code doesn't work:
firebase.database().ref($scope.language).orderByChild('word').equalTo($scope.word).remove()
.then(function(snapshot) {
console.log("Removed!");
})
The error message is:
TypeError: firebase.database(...).ref(...).orderByChild(...).equalTo(...).remove is not a function
The documentation makes remove() look simple. What am I missing?
You can only load data once you know its specific location in the JSON tree. To determine that location, you need to execute the query and loop through the matching results:
firebase.database().ref($scope.language).orderByChild('word').equalTo($scope.word).once("value").then(function(snapshot) {
snapshot.forEach(function(child) {
child.ref.remove();
console.log("Removed!");
})
});
If you only want to log after all have been removed, you can use Promise.all():
firebase.database().ref($scope.language).orderByChild('word').equalTo($scope.word).once("value").then(function(snapshot) {
var promises = [];
snapshot.forEach(function(child) {
promises.push(child.ref.remove());
})
Promise.all(promises).then(function() {
console.log("All removed!");
})
});
This is Frank's first code block with another closure. Without the closure the record is removed from the database but then there's an error message:
Uncaught (in promise) TypeError: snapshot.forEach(...).then is not a function
Adding a closure fixes the error message.
firebase.database().ref($scope.language).orderByChild('word').equalTo($scope.word).once("value").then(function(snapshot) {
snapshot.forEach(function(child) {
child.ref.remove();
}); // a closure is needed here
}).then(function() {
console.log("Removed!");
});
I have below script in asp.net mvc:
$.ajax({
url: "/MyController/MyAction/",
type: 'POST',
data: $("#Myform").serialize(),
success: function () {
// Do something
},
error: function () {
// Do something
},
complete: function () {
// Do something
},
beforeSend: function () {
// Do someting
}
});
This script calls to an action in the controller. The controller performs some actions and sometimes things go ok or not. If things went ok, I want success and complete options in the script get executed.No problem until here, but if in the controller there is an error or something I want to tell the script: "hey, there is an error!" and then the error option in the script to be executed. How to do this? Do I have to return something from the controller to the script to indicate an error has been generated in order to error option in the script gets executed?
Set the HTTP status code to 4xx or 5xx in the controller.
That will make you end up in the error callback.
As far as the AJAX request goes an error is an transfer/network error getting the page.
If you want to return an error either return it in the data then parse that and execute the error function inside the success part if you detect an error. Or as, Johan says, return an HTTP error code from the server.
Use try catch in your action like,
public ActionResult Sample()
{
try
{
return Json(new{status="success"},JsonRequestBehavior.AllowGet);
}
catch(Exception ex)
{
return Json(new{status="failed"},JsonRequestBehavior.AllowGet);
}
}
In your ajax call success check with condition like,
if(data.status=='success')
{
alert('All Happies');
}
else
{
alert('error came');
}
Hope this helps.
I am trying to figure out how to find out exact reason of (async) HttpRequest (from 'dart:html') failure, and, to be honest, I am a bit lost here.
The onError callback receives only HttpRequestProgressError object, which doesn't have anything useful, and the HttpRequest object itself has "status" set to "0" in case of failure, even console shows "Failed to load resource" with no details.
What I want is to know the exact reason - like "connection refused" or "host name not resolved".
Is this possible at all?
Thank you!
Unfortunately, there is no property to report the error as detailed as you'd like. The reason is that JavaScript doesn't support this.
There are the properties status and statusText on the HttpRequest object (which you could get from your HttpRequestProgressEvent with evt.target, but those represent HTTP status codes. Every other error has the status code 0 - request failed. This could be anything, and the only place to look at is the browser's console, because this is an Exception thrown by the browser.
If your request was synchronous, you could surround the send() with a try-catch. If your request is async, this won't work.
See here
#library('Request');
#import('dart:html');
#import("dart:json");
typedef void RequestHandler(String responseText);
typedef void ErrorHandler(String error);
class ResourceRequest {
XMLHttpRequest request;
RequestHandler _callbackOnSuccess;
ErrorHandler _callbackOnFailure;
ResourceRequest.openGet(String url, RequestHandler callbackOnSuccess, [ErrorHandler callbackOnFailure])
: request = new XMLHttpRequest(),
_callbackOnSuccess = callbackOnSuccess,
_callbackOnFailure = callbackOnFailure {
request.open("GET", url, async : true);
request.on.loadEnd.add((XMLHttpRequestProgressEvent e) => onLoadEnd(e));
}
void send() {
request.send();
}
void onLoadEnd(XMLHttpRequestProgressEvent event) {
if (request.readyState == 4 && request.status == 200) {
_callbackOnSuccess(request.responseText);
} else if (_callbackOnFailure != null) {
_callbackOnFailure(request.statusText);
}
}
}
I am trying to allow users to download a file, and have been trying for quite a while to no avail to get this to work.
The code I have been using is:
Response.ClearHeaders();
Response.Clear();
Response.BufferOutput = true;
Response.AddHeader("Content-disposition",
"attachment; filename= "+ Path.GetFileName(path) + fileType);
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(buffer);
Response.Flush();
Response.Close();
Response.End();
Unfortunately nothing happens when I try to make it run except for lots of exceptions:
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.Mvc.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.Mvc.dll
A first chance exception of type 'System.NullReferenceException' occurred in WebDev.WebHost40.dll
(etc)
Changing my debugging settings I discovered that the exception I was getting was
"Server cannot set content type after HTTP headers have been sent."
I have searched through Google and attempted many solutions but nothing have worked so far. This is the only time Response has been used as far as I know - unless there is some background processes occurring (if so, how do I change this?). Please note that I am using Asp.NET MVC.
Any ideas?
Edit:
Here is some context, which might help to resolve the problem:
The code is inside a Webmethod that has been called via Ajax, the reason being that I needed to call the server side via the client side (bad practice, but it was needed in the time provided) and I also needed to pass through a parameter.
Here is the ajax call:
$("#Button").each(function() {
this.submitting = false; //To prevent double-clicking problems
}).on("click", function (e) {
if (e.preventDefault) e.preventDefault();
$.ajaxSetup({ cache: false });
e.preventDefault();
if (!this.submitting)
{
this.submitting = true;
var self = this;
$.ajax({
url: 'Controller/retrieveFile',
type: 'POST',
data: { SystemNumber: $("#Button").val() },
dataType: 'json',
success: function (data) {
self.submitting = false;
},
error: function() {
self.submitting = false;
}
});
}
});
Is this, perhaps, a problem with the return value? Currently I am returning
Json(true, JsonRequestBehavior.AllowGet);
Try using HttpContext.Response.AppendHeader("Content-disposition", ....) and getting rid of the Response.ClearHeaders(); and Response.Clear(); lines.
Also you should consider using FileContentResult as the return type of your method.
As the title says, i want to retrieve my Json data values from a XMLHttpRequest. I already know how to do it by using a common success $.Ajax success event, but i want to get it's values from an error event. A thing that i noticed is not simple to find all kinds of a XMLHttpRequest types.
To explain a little more, here's the scenario: after some inactivity, the user sessions expires. If he tries to do any operations using an Ajax call, he'll be redirected to the login page. I handle this session timeout error on a particular filter that implements an OnException method.
While i can do it using a sort of a hack (by setting manually the HTTP response code), i'd like to do it on "proper way", with no hacks.
OnException method code snippet
filterContext.ExceptionHandled = true;
// If this is an ajax request, return the exception in the response
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
//If the session has expired, throws a SESSION TIMEOUT error
if (Session["UserLogged"] == null)
{
//The hack mentioned before
filterContext.HttpContext.Response.StatusCode = 502;
filterContext.Result = new JsonResult()
{
Data = new { success = false, errorType = "SESSION_TIMEOUT" ,error = filterContext.Exception.ToString() },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
So, by using a simple $.Ajax Error Event, how would i retrive the data from the filterContext.Result? Specifically the errorType parameter.
You should be able to parse the JSON data out of the jqXHR responseText property in your error handler.
error: function(jqXHR, textStatus, errorThrown) {
alert('jqXHR.responseText = ' + jqXHR.responseText);
}