I, am trying to create a global exception handling service for execution error not a http status error in asp.net core 2.1 web api and write to a file.
Tried few options like
services.AddMvc(config =>
{
config.Filters.Add(typeof(GlobalExceptionFilter));
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddSessionStateTempDataProvider();
Exception Class
public class GlobalExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext context)
{
HttpStatusCode status = HttpStatusCode.InternalServerError;
String message = String.Empty;
var exceptionType = context.Exception.GetType();
if (exceptionType == typeof(UnauthorizedAccessException))
{
message = "Unauthorized Access";
status = HttpStatusCode.Unauthorized;
}
else if (exceptionType == typeof(NotImplementedException))
{
message = "A server error occurred.";
status = HttpStatusCode.NotImplemented;
}
else if (exceptionType == typeof(MyAppException))
{
message = context.Exception.ToString();
status = HttpStatusCode.InternalServerError;
}
else
{
message = context.Exception.Message;
status = HttpStatusCode.NotFound;
}
context.ExceptionHandled = true;
HttpResponse response = context.HttpContext.Response;
response.StatusCode = (int)status;
response.ContentType = "application/json";
var err = message + " " + context.Exception.StackTrace;
response.WriteAsync(err);
}
}
But it never coming to the errors.I tried with debugging but never hit the debugging code.
can anyone please let me how to log the global error on file.
found some of the solution from this solutions https://blog.elmah.io/error-logging-middleware-in-aspnetcore/
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-2.1
http://www.talkingdotnet.com/global-exception-handling-in-aspnet-core-webapi/