I would like to know whether or not it is possible to clear an exception out of the request when trying to hit the Render Phase after the Action Phase has thrown the exception.
If you look at this code snippet from the doRenderService method of DispatchPortlet.class (a Spring provided class):
PortletSession session = request.getPortletSession(false);
if (session != null) {
if (request.getParameter(ACTION_EXCEPTION_RENDER_PARAMETER) != null) {
Exception ex = (Exception)
session.getAttribute(ACTION_EXCEPTION_SESSION_ATTRIBUTE);
if (ex != null) {
logger.debug("Render phase found exception caught during action phase - rethrowing it");
throw ex;
}
}
else {
session.removeAttribute(ACTION_EXCEPTION_SESSION_ATTRIBUTE);
}
}
You can see here that an exception gets put into the parameter map and there doesn't seem to be any way to clear it out.
What I would like to do is originally catch the Exception (what I am successfully doing), display an "Error Page" (what I am successfully doing), then display a button on that Error Page that allows the user to bring up the "Render Phase" page again so that he/she may be able to try their Action, again.
I've tried to create a filter, interceptor, new controller to clear the parameter, but it seems that the ParameterMap is an UnmodifiableCollection.
Any thoughts?
I actually was able to figure this out by doing the following in a render-phase filter:
session.setAttribute(ACTION_EXCEPTION_SESSION_ATTRIBUTE, null)
You can configure your org.springframework.web.portlet.DispatcherPortlet with setForwardActionException(false). This prevents spring from adding the Exception details in render parameters, or session.
Related
when internal Guidewire code throws an exception you get a nicely formatted error message box. However, when custom code throws an exception you are directed to the error page (with the red stack trace text & back to application button). Is there anything in the Guidewire framework to make proper UI handling of errors nicer?
such as: < TextBox value="user.someMethod()"/>
//someMethod code...
try{
return user.someOtherCode()
}catch(e : Exception){
//TODO: gracefully display erorr mesage on page
//e.g. showErrorMessage()
return null
}
You have a simpler way to do this,
The below piece of code can be written in helper class or any Enhancement or even in PCF code tab, this will return a nice formatted error message.
gw.api.util.LocationUtil.addRequestScopedErrorMessage("Your error message")
After some searching through Guidewire OOTB code UserDisplayableExceptions are what you need - answering myself in case someone else has this thought.
function goToPolicy(bulkDocumentDownload : BulkDocDownload_Avi) {
try {
throw new IndexOutOfBoundsException("Ops! some index out of bounds exception was thrown")
} catch (e : Exception) {
throw new com.guidewire.pl.web.controller.UserDisplayableException(e.Message)
}
}
I have an exception handling in my application very similar to this solution:
http://www.devcurry.com/2012/06/aspnet-mvc-handling-exceptions-and-404.html
There is a nasty bug in my app where it is possible for the sql to deadlock with an other process. This happens rarely (1-2 requests fail daily because of this), but it still happens.
How can I automatically refresh the page on sql deadlock (and hide the error this way from the end user on get requests)?
Can I do it in the Application_Error function? Or in the overridden OnException in HandleErrorAttribute?
EDIT:
I mocked up some code in the BaseController I created:
protected override void OnException(ExceptionContext filterContext)
{
Exception ex = filterContext.Exception;
SqlException sex = ex as SqlException;
if (sex != null && sex.Number == 1205)
{
Log.Error("Transaction deadlocked with the following exception:");
Log.Exception(sex);
//I need to write the logic that refreshes the page here.
}
else
{
Log.Error("Application error with the following exception:");
Log.Exception(ex);
}
base.OnException(filterContext);
}
I need help on the refresh part.
I would deal with it by overriding the OnException() method of the controller. It would be best if you inherit all your controllers from a custom base one in which the override is done to maintain uniformity and DRYness of the solution.
just add bellow code, before base.OnException(filterContext);
// Stop any other exception handlers from running
filterContext.ExceptionHandled = true;
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")));
I'm working on a team-project and I am in the following situation:
I created my own Exception class, and I want all the thrown exceptions of type myException to be handled and automatically redirected to the Error view where I would nicely display the error, which is ok to do. This is what I added in my Web.config:
<customErrors mode="On" defaultRedirect="Error" />
The issue is I want all the rest of the exceptions to be thrown normally, seeing all the information about it, including the stack trace, the source file and the line error, which would be really good for the team-project.
I've tried the [HandleError(ExceptionType=typeof(myException)], but it is no use.
I also tried to override the OnException function of the controller and if the exception is not myException then i would throw it again, but i still get in the Error view.
protected override void OnException(System.Web.Mvc.ExceptionContext filterContext)
{
if (filterContext.Exception.GetType() != typeof(myException)) {
throw filterContext.Exception;
}
base.OnException(filterContext);
}
Any idea which could work?
Thanks.
You may get the result you want by leaving custom errors Off (so that for all the errors you get the stack trace displayed), and redirecting the exceptions you want to the controller/view you need (so that a friendly-looking page will be displayed).
You could define a base controller for all your controllers, and override its OnException method with something like below:
if (filterContext.Exception.GetType() == typeof(YourCustomException))
{
filterContext.ExceptionHandled = true;
filterContext.Result = RedirectToAction("ActionName", "ControllerName", new { customMessage = "You may want to pass a custom error message, or any other parameters here"});
}
else
{
base.OnException(filterContext);
}
I've implemented an ActionFilterAttribute responsible for NHibernate transaction management. Transactions are committed in the OnResultedExecuted override, which occasionally will result in an exception being thrown.
I'm able to successfully intercept these exceptions in the controllers OnException override, however the page still redirects as if the transaction were successful.
What I'd like to be able to do is return the same view action that caused the error with the exceptions message added to the ModelState.
I've tried a number of different things, none of which seem to work.. here's my latest attempt:
[HttpPost]
[Transaction]
[HandleError]
public ActionResult Enroll(EnrollNewEmployeeCommand command)
{
if(command.IsValid())
{
try
{
_commandProcessor.Process(command);
}
catch(Exception exception)
{
ModelState.AddModelError("", exception.Message);
return View(command);
}
return this.RedirectToAction(x => x.Index()); // redirects to index even if an error occurs
}
return View(command);
}
protected override void OnException(ExceptionContext filterContext)
{
//dont interfere if the exception is already handled
if (filterContext.ExceptionHandled)
return;
ModelState.AddModelError("", filterContext.Exception.Message);
filterContext.ExceptionHandled = true;
// want to return original view with updated modelstate
filterContext.Result = new ViewResult
{
ViewName = filterContext.RequestContext.RouteData.Values["action"].ToString(),
ViewData = filterContext.Controller.ViewData
};
}
What I'd like to be able to do is return the same view action that caused the error with the exceptions message added to the ModelState
You can't. OnResultedExecuted happens too late. The view rendering has ended and you can no longer modify what will be sent to the client at this stage.
Your last chance if you want to still be able to modify the returned result to the client is OnResultExecuting. So you could commit your transactions there. Wouldn't be so penalizing I guess.
At the contrary, I would even commit transactions in the OnActionExecuted event, as at this stage all you've got should be a fully initialized view models passed to the view for rendering. That's where your transaction boundaries should end. The process of rendering of the views should be excluded from any transactions and DB stuff. It's just HTML (or something) rendering from a view model, plain and simple.