I placed the following code in the global file to catch exception in my mvc application:
void Application_Error(Object sender, EventArgs e)
{
Exception ex = Server.GetLastError().GetBaseException();
log.Error("Exception", ex);
}
and the following to trace what controllers are called:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (log.IsDebugEnabled)
{
var loggingWatch = Stopwatch.StartNew();
filterContext.HttpContext.Items.Add(StopwatchKey, loggingWatch);
var message = new StringBuilder();
message.Append(string.Format("Executing controller: {0}, action: {1}",
filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
filterContext.ActionDescriptor.ActionName));
log.Debug(message);
}
}
Is there more I can do to catch errors involving db, security (like cannot connect to ldap), data issues/casting, etc..?
The second code snippet could be added to a global action filter (registered in global.asax). The first snippet could be added to a seperate IHttpModule implementation to remove it from global.asax.
Other than that you've added code to the two places where all exceptions will be caught. The first one will be invoked for all non-MVC related exceptions while the later one is for MVC exceptions only (routing excluded)
Related
We have a global.asax.cs file which contains this code...
Approach One
public class WebApiApplication : System.Web.HttpApplication
{
TelemetryClient _telemetry = new TelemetryClient(new Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration() {
InstrumentationKey = EnvironmentHelper.InstrumentationKey,
ConnectionString = EnvironmentHelper.AppInsightsConnectionString
});
protected void Application_Start()
{
HttpConfiguration config = GlobalConfiguration.Configuration;
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
I am concerned that this will not log every and all exceptions to Insights. Would it be better to use this code?...
Approach Two
public class WebApiApplication : System.Web.HttpApplication
{
TelemetryClient _telemetry = new TelemetryClient(...);
protected void Application_Start()
{
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Filters.Add(new CustomExceptionFilter()); // ADDED LINE
GlobalConfiguration.Configure(WebApiConfig.Register);
}
protected void Application_Error(Object sender, EventArgs e) // ADDED METHOD
{
Exception appException = Server.GetLastError();
_telemetry.TrackException(appException);
}
}
// ADDED CLASS
public class CustomExceptionFilter : ExceptionFilterAttribute
{
TelemetryClient _telemetry = new TelemetryClient(...);
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
_telemetry.TrackException(actionExecutedContext.Exception);
base.OnException(actionExecutedContext);
}
}
Are these approaches equal or is one more reliable?
Not sure what do you mean all exceptions get logged.
Actually, Application Insights will auto collect unhandled exceptions thrown in the controller methods automatically for WebAPI 2+, exception the following scenario:
Exceptions thrown from controller constructors.
Exceptions thrown from message handlers.
Exceptions thrown during routing.
Exceptions thrown during response content serialization.
Exception thrown during application start-up.
Exception thrown in background tasks.
And For the other exceptions which are handled by application, still need to be tracked manually. You can use the telemetryclient to track these exceptions.
The referenced doc is here.
As far as I know I have followed exactly the instructions:
I have set everything up as suggested. Used my secret key, enabled crashes. Had the set up checked by another developer and see the crash happened in appcenter.ms but still I never see any attached information.
Here's an example:
public class Application
{
// This is the main entry point of the application.
static void Main(string[] args)
{
// if you want to use a different Application Delegate class from "AppDelegate"
// you can specify it here.
try
{
UIApplication.Main(args, null, "AppDelegate");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Crashes.TrackError(ex,
new Dictionary<string, string> {
{"Main", "Exception"},
{"Device Model", DeviceInfo.Model },
});
throw;
}
}
}
No matter what, when and how my application crashes I still will not get the attached information.
I am wondering has anyone got the attached data for crashes to work with XF ?
We can use AppCenter only after it has been started which according to official documentation on iOS we do it in AppDelegate class in the method FinishedLaunching. But the point is the class Application in Main.cs file is called before AppDelegate class.
If you want to see the attached info then you can try it for example in a XAML code-behind file by manually throwing an exception. Here is an example for a button's click event:
private void TheButton1_OnClicked(object sender, EventArgs e)
{
try
{
throw new DivideByZeroException("Testing attached info!");
}
catch (Exception exception)
{
Crashes.TrackError(exception,
new Dictionary<string, string> {{"Device Model", "My device model" }});
}
}
The attached info on TrackError() method i.e properties dictionary works on both Android and iOS. To see that info you need to go through this in App Center's panel:
From left panel choose Diagnostics.
From Groups section choose your specific group.
From tabs in top section choose Reports.
Choose your specific device.
The attached info is In Stacktrace tab and in Error properties section.
Just to correct, the additional data you attach with exception in TrackError method are mostly in catch blocks or generated exception in TrackError methods, so it will only displayed with those manually logged(TrackError) exceptions.
Crashes are exceptions that are not handled and logged automatically by appcenter so if you look in crash reports there will not be any attached data available.
Additional data sent with exception as properties can be found in reports section of error on appcenter.
I am sure you have initialized Crash service in OnStart method of App.xaml.cs class with correct app secrets and required platforms(android/ios).
I was able to track the crashes. The only difference is am tracking it from the native projects.
For Android in the MainActivity:
protected override void OnCreate(Bundle savedInstanceState)
{
...
AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
TaskScheduler.UnobservedTaskException += TaskSchedulerOnUnobservedTaskException;
AndroidEnvironment.UnhandledExceptionRaiser += AndroidEnvironment_UnhandledExceptionRaiser;
...
}
private void AndroidEnvironment_UnhandledExceptionRaiser(object sender, RaiseThrowableEventArgs e)
{
var newExc = new Exception("UnhandledExceptionRaiser", e.Exception as Exception);
LogUnhandledException(newExc);
}
private static void TaskSchedulerOnUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs unobservedTaskExceptionEventArgs)
{
var newExc = new Exception("TaskSchedulerOnUnobservedTaskException", unobservedTaskExceptionEventArgs.Exception);
LogUnhandledException(newExc);
}
private static void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs unhandledExceptionEventArgs)
{
var newExc = new Exception("CurrentDomainOnUnhandledException", unhandledExceptionEventArgs.ExceptionObject as Exception);
LogUnhandledException(newExc);
}
internal static void LogUnhandledException(Exception exception)
{
try
{
Crashes.TrackError(exception);
...
}
catch (Exception ex)
{
// just suppress any error logging exceptions
}
}
For iOS in the AppDelegate:
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
...
AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
TaskScheduler.UnobservedTaskException += TaskSchedulerOnUnobservedTaskException;
...
}
private static void TaskSchedulerOnUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs unobservedTaskExceptionEventArgs)
{
var newExc = new Exception("TaskSchedulerOnUnobservedTaskException", unobservedTaskExceptionEventArgs.Exception);
LogUnhandledException(newExc);
}
private static void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs unhandledExceptionEventArgs)
{
var newExc = new Exception("CurrentDomainOnUnhandledException", unhandledExceptionEventArgs.ExceptionObject as Exception);
LogUnhandledException(newExc);
}
internal static void LogUnhandledException(Exception exception)
{
try
{
...
}
catch
{
// just suppress any error logging exceptions
}
}
I'm trying to create a unified error handling/reporting in ASP.NET Web API 2.1 Project built on top of OWIN middleware (IIS HOST using Owin.Host.SystemWeb).
Currently I used a custom exception logger which inherits from System.Web.Http.ExceptionHandling.ExceptionLogger and uses NLog to log all exceptions as the code below:
public class NLogExceptionLogger : ExceptionLogger
{
private static readonly Logger Nlog = LogManager.GetCurrentClassLogger();
public override void Log(ExceptionLoggerContext context)
{
//Log using NLog
}
}
I want to change the response body for all API exceptions to a friendly unified response which hides all exception details using System.Web.Http.ExceptionHandling.ExceptionHandler as the code below:
public class ContentNegotiatedExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
var errorDataModel = new ErrorDataModel
{
Message = "Internal server error occurred, error has been reported!",
Details = context.Exception.Message,
ErrorReference = context.Exception.Data["ErrorReference"] != null ? context.Exception.Data["ErrorReference"].ToString() : string.Empty,
DateTime = DateTime.UtcNow
};
var response = context.Request.CreateResponse(HttpStatusCode.InternalServerError, errorDataModel);
context.Result = new ResponseMessageResult(response);
}
}
And this will return the response below for the client when an exception happens:
{
"Message": "Internal server error occurred, error has been reported!",
"Details": "Ooops!",
"ErrorReference": "56627a45d23732d2",
"DateTime": "2015-12-27T09:42:40.2982314Z"
}
Now this is working all great if any exception occurs within an Api Controller request pipeline.
But in my situation I'm using the middleware Microsoft.Owin.Security.OAuth for generating bearer tokens, and this middleware doesn't know anything about Web API exception handling, so for example if an exception has been in thrown in method ValidateClientAuthentication my NLogExceptionLogger not ContentNegotiatedExceptionHandler will know anything about this exception nor try to handle it, the sample code I used in the AuthorizationServerProvider is as the below:
public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
{
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
//Expcetion occurred here
int x = int.Parse("");
context.Validated();
return Task.FromResult<object>(null);
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
if (context.UserName != context.Password)
{
context.SetError("invalid_credentials", "The user name or password is incorrect.");
return;
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
context.Validated(identity);
}
}
So I will appreciate any guidance in implementing the below 2 issues:
1 - Create a global exception handler which handles only exceptions generated by OWIN middle wares? I followed this answer and created a middleware for exception handling purposes and registered it as the first one and I was able to log exceptions originated from "OAuthAuthorizationServerProvider", but I'm not sure if this is the optimal way to do it.
2 - Now when I implemented the logging as the in the previous step, I really have no idea how to change the response of the exception as I need to return to the client a standard JSON model for any exception happening in the "OAuthAuthorizationServerProvider". There is a related answer here I tried to depend on but it didn't work.
Here is my Startup class and the custom GlobalExceptionMiddleware I created for exception catching/logging. The missing peace is returning a unified JSON response for any exception. Any ideas will be appreciated.
public class Startup
{
public void Configuration(IAppBuilder app)
{
var httpConfig = new HttpConfiguration();
httpConfig.MapHttpAttributeRoutes();
httpConfig.Services.Replace(typeof(IExceptionHandler), new ContentNegotiatedExceptionHandler());
httpConfig.Services.Add(typeof(IExceptionLogger), new NLogExceptionLogger());
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new AuthorizationServerProvider()
};
app.Use<GlobalExceptionMiddleware>();
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
app.UseWebApi(httpConfig);
}
}
public class GlobalExceptionMiddleware : OwinMiddleware
{
public GlobalExceptionMiddleware(OwinMiddleware next)
: base(next)
{ }
public override async Task Invoke(IOwinContext context)
{
try
{
await Next.Invoke(context);
}
catch (Exception ex)
{
NLogLogger.LogError(ex, context);
}
}
}
Ok, so this was easier than anticipated, thanks for #Khalid for the heads up, I have ended up creating an owin middleware named OwinExceptionHandlerMiddleware which is dedicated for handling any exception happening in any Owin Middleware (logging it and manipulating the response before returning it to the client).
You need to register this middleware as the first one in the Startup class as the below:
public class Startup
{
public void Configuration(IAppBuilder app)
{
var httpConfig = new HttpConfiguration();
httpConfig.MapHttpAttributeRoutes();
httpConfig.Services.Replace(typeof(IExceptionHandler), new ContentNegotiatedExceptionHandler());
httpConfig.Services.Add(typeof(IExceptionLogger), new NLogExceptionLogger());
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new AuthorizationServerProvider()
};
//Should be the first handler to handle any exception happening in OWIN middlewares
app.UseOwinExceptionHandler();
// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
app.UseWebApi(httpConfig);
}
}
And the code used in the OwinExceptionHandlerMiddleware as the below:
using AppFunc = Func<IDictionary<string, object>, Task>;
public class OwinExceptionHandlerMiddleware
{
private readonly AppFunc _next;
public OwinExceptionHandlerMiddleware(AppFunc next)
{
if (next == null)
{
throw new ArgumentNullException("next");
}
_next = next;
}
public async Task Invoke(IDictionary<string, object> environment)
{
try
{
await _next(environment);
}
catch (Exception ex)
{
try
{
var owinContext = new OwinContext(environment);
NLogLogger.LogError(ex, owinContext);
HandleException(ex, owinContext);
return;
}
catch (Exception)
{
// If there's a Exception while generating the error page, re-throw the original exception.
}
throw;
}
}
private void HandleException(Exception ex, IOwinContext context)
{
var request = context.Request;
//Build a model to represet the error for the client
var errorDataModel = NLogLogger.BuildErrorDataModel(ex);
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.ReasonPhrase = "Internal Server Error";
context.Response.ContentType = "application/json";
context.Response.Write(JsonConvert.SerializeObject(errorDataModel));
}
}
public static class OwinExceptionHandlerMiddlewareAppBuilderExtensions
{
public static void UseOwinExceptionHandler(this IAppBuilder app)
{
app.Use<OwinExceptionHandlerMiddleware>();
}
}
There are a few ways to do what you want:
Create middleware that is registered first, then all exceptions will bubble up to that middleware. At this point just write out your JSON out via the Response object via the OWIN context.
You can also create a wrapping middleware which wraps the Oauth middleware. In this case it will on capture errors originating from this specific code path.
Ultimately writing your JSON message is about creating it, serializing it, and writing it to the Response via the OWIN context.
It seems like you are on the right path with #1. Hope this helps, and good luck :)
The accepted answer is unnecessarily complex and doesn't inherit from OwinMiddleware class
All you need to do is this:
public class HttpLogger : OwinMiddleware
{
public HttpLogger(OwinMiddleware next) : base(next) { }
public override async Task Invoke(IOwinContext context)
{
await Next.Invoke(context);
Log(context)
}
}
Also, no need to create extension method.. it is simple enough to reference without
appBuilder.Use(typeof(HttpErrorLogger));
And if you wanna log only specific requests, you can filter on context properties:
ex:
if (context.Response.StatusCode != 200) { Log(context) }
I created servlet to download file from a server. In GWT I created a FormPanel and I am able to download a file.
Problem is, that I want to fire an event, when the file is ready. I tried to use onSubmitComplete event, but it isn't firing.
I found a suggestion, to change ContetType to "text/html", but still no luck. I found, that the problem lies in writing to OutputStream - when commented out, event is fired.
Here is my servlet code
public void handleRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
response.setHeader("Content-Disposition", "attachment; filename=File.xls");
HSSFWorkbook workbook = new HSSFWorkbook();
try {
workbook = fileCreator.getWorkbook();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
OutputStream out = response.getOutputStream();
workbook.write(out);
out.close();
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().print("something");
response.flushBuffer();
}
So file is downloaded successfully, but event is not triggered. Even when I just get OutputStream and close it (without writing to it), event stops working.
When I remove whole "writing-to-output-stream" code, event works like a charm.
Any suggestions?
UPDATE
Here is code for FormPanel and its handlers, meby there is a problem?
Form:
downloadFileFormPanel.setEncoding(FormPanel.ENCODING_URLENCODED);
downloadFileFormPanel.setMethod(FormPanel.METHOD_POST);
VerticalPanel panel = new VerticalPanel();
panel.setWidth(UIConstatns.SIZE_100percent);
downloadFileFormPanel.setWidget(panel);
downloadFileButton = new Button(messages.EXPORT_LIMITS());
downloadFileButton.setWidth(UIConstatns.SIZE_100percent);
downloadFileButton.addStyleName("navigation-button");
panel.add(downloadFileButton);
Handlers
private void registerExportLimitsHandler() {
registerHandler(getView().getDownloadFileButton().addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
getView().showLoadingDialog();
getDownloadFileForm().submit();
}
}));
}
private void registerFormSubmitCompleteHandler() {
getView().getDownloadFileForm().addSubmitCompleteHandler(new SubmitCompleteHandler() {
public void onSubmitComplete(SubmitCompleteEvent event) {
Window.alert("download complete");
getView().hideLoadingDialog();
}
});
}
According to the Javadoc of ServletResponse#getWriter() you can either use response.getOutputStream() or response.getWriter() to write the body of the response, but not both. Furthermore it is better to set the status code of the response before writing the body. Please try the following:
// ...
response.setStatus(HttpServletResponse.SC_OK);
OutputStream out = response.getOutputStream();
workbook.write(out);
out.flush();
out.close();
// response.getWriter().print("something");
// response.flushBuffer();
You did not post the line where you create your FormPanel so I'm not sure if this was your problem:
Looks like the FormPanel(String target) constructor does not work with the SubmitCompleteHandler. With the default constructor it seems to work.
I'm pretty new to MVC ASP.NET. I read about OnException override method. I'm thinking, whether I should put try catch {throw} on Controller or Model in order for OnException to be invoked. OR, I try catch not required, OnException will be invoked autmatically if any exception occurs?
Thanks Heaps.
"Called when an unhandled exception occurs in the action."
http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.onexception.aspx
If you don't handle (i.e. "catch") an exception, the OnException method should be called.
I ended up doing this:
Created LogAndRedirectOnErrorAttribute class that uses abstract class FilterAttribute and implements IExceptionFilter as shown below:
public class LogAndRedirectOnErrorAttribute : FilterAttribute,IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
//Do logging here
Util.LogError(Utility.GetExceptionDetails(filterContext.Exception), TraceEventType.Critical.ToString());
//redirect to error handler
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(
new { controller = "Error", action = "Index" }));
// Stop any other exception handlers from running
filterContext.ExceptionHandled = true;
// CLear out anything already in the response
filterContext.HttpContext.Response.Clear();
}
}
And on Each Controller Class where necessary, use the above attribute:
[LogAndRedirectOnError]
public class AccountController:Controller
{
.....
}