So basicly im getting this error and its pretty straightforward what it means, my trouble is understanding where it is. The stack trace only points to this method.
async Task GetInfo(string response)
{
var newData= JsonConvert.DeserializeObject<>(response);
this.NewData= newData;
this.MyDataForm.NewData= this.NewData;
if (this.NewData.Age!= this.Age|| this.NewData.Id!= this.Id)
{
await RequestNewData();
}
else
{
//TODO
}
}
This method is inside a try catch within the RequestNewData(); Right now my only guess for what may have been throwing this null exception is that MyDataForm is null at some point.
Related
I have a Spring boot service with some code like below for parallel async call:
CompletableFuture future1 = accountManager.getResult(url1);
CompletableFuture future2 = accountManager.getResult(url2);
CompletableFuture.allOf(future1, future2).join();
String result1 = future1.get();
String result2 = future2.get();
It works fine when there is no exception. My question is how to handle exception? If getting future1 failed (let say url2 is an invalid url), I still want future2 back as partial result of allOf method. How should I do it?
Thanks!
CompletableFuture comes with a block called exceptionally() which can be used handle the exceptions happen inside the asynchronous code block. Snippet of getResult method for your reference,
public CompletableFuture<String> getGreeting(String url) {
return CompletableFuture.supplyAsync( () -> {
return // Business logic..
}, executor).exceptionally( ex -> {
log.error("Something went wrong : ", ex);
return null;
});
}
In this case the block would return null in case of exception and allOf method would lead to a completion where you can filter the one resulted in the exception when you fetch individual futures.
In code below I am fetching some data. If error/exception was thrown I want the exception handler to catch it. Once done with fetching, I am posting the result using LiveData to whoever is observing.
What I am trying to achieve is that the exception handler to finish its job once I post the result. Which means, if the observer handling the result also throws an exception, I don't want the coroutine exception handler to catch it (Which is the case in code below).
fun loadPrerequisites(resultObserver: MutableLiveData<PrerequisiteDataHolder?>) {
val exceptionHandler = CoroutineExceptionHandler { _, throwable ->
resultObserver.postValue(null)
}
scope.launch(Dispatchers.IO + exceptionHandler) {
val deferredCreationScheme = async {
fetchCreationScheme()
}
val creationScheme = deferredCreationScheme.await()
//TODO remove exception handler at this stage?
resultObserver.postValue(PrerequisiteDataHolder(creationScheme))
}
}
Is there a way to remove the exception handler before posting the result to the LiveData? Or must I introduce a new scope?
You seem to have misunderstood the purpose of the coroutine exception handler. It is the coroutine equivalent of uncaughtExceptionExceptionHandler in Java and its purpose is to inform you of an exception that has already broken its coroutine. You seem to want to use it to implement business logic-level exception handling.
The coroutine exception handler is not a replacement for the try-catch block, and the latter is what you should use in your case.
I think you don't need async in your code in the first place, I believe this is all you really need:
scope.launch(Dispatchers.IO) {
resultObserver.postValue(
try {
PrerequisiteDataHolder(fetchCreationScheme())
} catch (e: Exception) {
null
}
)
}
I typically use a helper function for code like this:
inline fun <T> tryOrNull(block: () -> T) = try {
block()
} catch (t: Throwable) {
null
}
Then your code becomes
scope.launch(Dispatchers.IO) {
tryOrNull { PrerequisiteDataHolder(fetchCreationScheme()) }
.also { resultObserver.postValue(it) }
}
I have a partial view which loads a ObjectResult from a SQL procedure. This is using the built in EF method.
public virtual ObjectResult<Something_Result> getSomething()
{
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<Something_Result>("getSomething");
}
So a usual problem is timeouts from the database and I would like to show this. But I cant seem to find this in the exception object from the Ajax.Load() functon .
In the responseText I only get "{"message":"An error occurred while executing the command definition. See the inner exception for details."}" and with status: 500
So is it an easy way to get the inner exception aswell?
Here is the exception thrown by the Ajax.load() function http://i.imgur.com/ZIrTrMU.jpg
And here is the Inner Exception from EF: http://i.imgur.com/LgOhOlB.png
You can put a try catch block in your Data access Layer where you are calling the getSomething method and send appropriate response text up the stack. Depending on where you are putting the catch block, you can check if:
if(ex.Number == -2)
or
if(ex.InnerException != null && ex.InnerException.Number == -2)
return Json(new { successful = false, Message = "Timeout" });
and return appropriate response text as a Json response or if only want to handle TimeOutException you can put in the specific catch block for 'Timeout Exception'
catch(TimeoutException ex)
{ return Json(new { successful = false, Message = "Timeout" }); }
I've read the question Handle ViewExireException/ajax and display a Primefaces dialog and the answer from BalusC. I'd want to handle the ViewExpiredException by showing the alert with information to refresh the page. I've taken the suggestion from BalusC to user RequestContextto put JavaScript to execute, and I've removed the JSF redirection because I'm not using it:
#Override
public void handle() throws FacesException {
for (Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator(); i.hasNext();) {
ExceptionQueuedEvent event = i.next();
ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();
Throwable t = context.getException();
if (t instanceof ViewExpiredException) {
ViewExpiredException vee = (ViewExpiredException) t;
try {
log.info("Catched ViewExpiredException for view {}", vee.getViewId());
RequestContext.getCurrentInstance().execute("handleViewExpired("+vee.getViewId()+")");
return;
} finally {
i.remove();
}
}
}
// At this point, the queue will not contain any ViewExpiredEvents.
// Therefore, let the parent handle them.
getWrapped().handle();
}
The problem is, I got NullPointerException when executing the handle method from wrapped handler. I've added the return clause, and after adding it, the effect was the same:
[30.01.13 15:45:59:140 CET] 0000002e ErrorPageWrit E An exception
occurred
javax.faces.FacesException: java.lang.NullPointerException at
org.apache.myfaces.shared_impl.context.ExceptionHandlerImpl.wrap(ExceptionHandlerImpl.java:241) at
org.apache.myfaces.shared_impl.context.ExceptionHandlerImpl.handle(ExceptionHandlerImpl.java:156)
at
my.project.web.handler.ViewExpiredExceptionExceptionHandler.handle(ViewExpiredExceptionExceptionHandler.java:59)
at
org.apache.myfaces.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:191)
at
org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
So, the parent handle method is executed, thought there should be the return from method (The info string is logged).
I'm using PrimeFaces 3.4 and MyFaces 2.0.7, everything on WebSphere 7.
I don't understand what is happening here. Is it possible to achieve what I want, and if so, what I'm doing wrong?
The best way was to handle that exception on client side. It's very simple few-liner and it's completly transparent:
var originalPrimeFacesAjaxResponseFunction = PrimeFaces.ajax.AjaxResponse;
PrimeFaces.ajax.AjaxResponse = function(data, status, xhr) {
var errorName = $(data.documentElement).find("error-name").text();
if (errorName == 'javax.faces.application.ViewExpiredException') {
alert('View has expired, redirection will follow');
window.location.reload();
} else {
originalPrimeFacesAjaxResponseFunction.apply(this, arguments);
}
};
No 2 new classes on server, no faces-config.xml changes, this is what I love in programming.
I need some Elmah logging in a async task executing on my webserver. But when I try to log the error it fails because of the HttpContext.
var httpContext = HttpContext.Current;
Task.Factory.StartNew(() =>
{
HttpContext.Current = httpContext;
try
{
//Execute some code
}
catch (Exception ex)
{
//Generate some error for the user and log the error in Elmah
try
{
ErrorLog.GetDefault(HttpContext.Current).Log(new Error(ex));
}
catch(Exception ex)
{
}
}
});
To get the progress for the task I implemented some polling mechanism. Currently none of the errors are logged to Elmah which make it difficult to solve them.
Also providing the context as parameter doesn't work.
It doesn't work. I get an ArgumentException telling me the expected value doesn't fall within the expected range. With the following stacktrace:
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
at System.Web.Hosting.IIS7WorkerRequest.GetServerVariableInternal(String name)
at System.Web.HttpRequest.AddServerVariableToCollection(String name)
at System.Web.HttpRequest.FillInServerVariablesCollection()
at System.Web.HttpServerVarsCollection.Populate()
at System.Web.HttpServerVarsCollection.Get(String name)
at Elmah.ErrorLog.InferApplicationName(HttpContext context)
at Elmah.ErrorLog.GetDefaultImpl(HttpContext context)
at Elmah.ServiceContainer.GetService(Type serviceType)
at Elmah.ServiceCenter.GetService(Object context, Type serviceType)
at Elmah.ErrorLog.GetDefault(HttpContext context)
at Bis.Utilities.Log.ElmahErrorLog.TryLogError(Exception exeption) in D:\Users\A500535\Documents\Projecten\Biobank\Bis\src\Utilities\Log\ElmahErrorLog.cs:line 13
Below is one ugly hack that might get the job done. Essentially, it creates an Error object on a bogus Exception (the prototype) so that the context can be captured while the request is still in flight. Later, when the task started as a result of the request fails, another Error object is created off the actual exception that occurred and then the interesting and contextual bits are selectively copied off the earlier prototype. Unfortunately, the prototype Error has to be created whether or not an exception will occur.
// Create an error that will capture the context
// and serve as a prototype in case a real exception
// needs logging
var prototype = new Error(new Exception(), context);
Task.Factory.StartNew(() =>
{
try
{
// Execute some code
}
catch (Exception ex)
{
// Generate some error for the user and log the error in ELMAH
try
{
// Create a new error without contextual information
// but then copy over the interesting bits from the
// prototype capture at time of request.
var error = new Error(ex)
{
HostName = prototype.HostName,
User = prototype.User,
};
error.ServerVariables.Add(prototype.ServerVariables);
error.QueryString.Add(prototype.QueryString);
error.Cookies.Add(prototype.Cookies);
error.Form.Add(prototype.Form);
ErrorLog.GetDefault(null).Log(error);
}
catch(Exception)
{
}
}
});
When you start a new thread it doesn't get the HttpContext structure. Since Elmah logging requires the HttpContext data, it will fail.
See the following QA:
Elmah Does not email in a fire and forget scenario
for me this worked in a async task called with Task.Run:
Elmah.ErrorLog.GetDefault(null).Log(new Elmah.Error(new NotSupportedException("elmah logging test")));