I've implemented a custom exception filter based on this blog post https://blog.kloud.com.au/2016/03/23/aspnet-core-tips-and-tricks-global-exception-handling/ .
I now noticed that I cannot get the file name or the line number where the exception occurred from StackFrame; the value for method GetFileLineNumber is always 0.
A quick example of what I tried:
StackTrace trace = new StackTrace(exception, true);
StackFrame[] stackFrames = trace.GetFrames();
if (stackFrames != null) {
foreach (StackFrame traceFrame in stackFrames) {
sourceFile = traceFrame.GetFileName();
sourceLineNumber = traceFrame.GetFileLineNumber();
}
}
Just to mention: GetFileName returns also null, but I can get the namespace and class name from various locations, so it's not a problem.
Noticed somewhere that I should have the PDB file on the folder for this to work and I checked that I already have it. And even if it worked, this should work in production environment as well.
Tried also using Caller Information (https://msdn.microsoft.com/en-us/library/mt653988.aspx) but there's a bit different problem. The exception filter has to implement IExceptionFilter interface and use it's method. Therefore I cannot add the attributes even if they are optional.
Here's the code part from Startup.cs:
public void ConfigureServices(IServiceCollection services) {
...
services.AddMvc(config => {
config.Filters.Add(new ApplicationExceptionFilter());
});
}
And here's the custom Filter
public class ApplicationExceptionFilter : IExceptionFilter {
public void OnException(ExceptionContext context) {
ApplicationExceptionHandler.handleException(context.HttpContext, context.Exception);
}
}
And what I tried for getting the Caller Information was:
public void OnException(ExceptionContext context,
[System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0) {
But that will not work since it doesn't implement the interface anymore.
How can I get the line number while still handling the exceptions in a single place?
Assumed that my problem is the fact that I'm not getting line number from stack trace and reproduced the problem with:
public ActionResult ServerError() {
Int32 x = 0;
try {
return Content((1 / x).ToString());
} catch (Exception ex) {
StackTrace trace = new StackTrace(ex, true);
StackFrame[] stackFrames = trace.GetFrames();
if (stackFrames != null) {
foreach (StackFrame traceFrame in stackFrames) {
String sourceFile = traceFrame.GetFileName();
int sourceLineNumber = traceFrame.GetFileLineNumber();
}
}
}
return Content("");
}
Still not getting values for sourceFile (it's null) or sourceLineNumber (it's 0).