Reputation: 2997
In my MVC 5 application unhandled exception are capture within the Global Application_Error
event and then redirected to ErrorController
.
The last error is added to HttpApplicationState
in the Global.Error event and retrieved in the Controller.
MVC 6 doesn't have the Global file. it uses the IExceptionFilter
in capturing the unhandled exception.
public class GlobalExceptionFilter : IExceptionFilter, IDisposable {
private readonly ILogger logger;
private bool _disposed;
public GlobalExceptionFilter(ILoggerFactory logger) {
if (logger == null) {
throw new ArgumentNullException(nameof(logger));
}
this.logger = logger.CreateLogger("Global Exception Filter");
}
public void OnException(ExceptionContext context) {
logger.LogError("GlobalExceptionFilter", context.Exception);
//redirect to controller
}
public void Dispose() {
if (this._disposed) {
return;
}
this._disposed = true;
}
private static int GetHttpStatusCode(Exception ex) {
if (ex is HttpResponseException) {
return (int)(ex as HttpResponseException).HttpStatusCode;
}
return (int)HttpStatusCode.InternalServerError;
}
}
Is it possible to do the same in OnException
?
Upvotes: 2
Views: 1935
Reputation: 2754
From asp.net core documentation (check here)
In general, filters are meant to handle cross-cutting business and application concerns. This is often the same use case for middleware. Filters are very similar to middleware in capability, but let you scope that behavior and insert it into a location in your app where it makes sense, such as before a view, or after model binding. Filters are a part of MVC, and have access to its context and constructs. For instance, middleware can’t easily detect whether model validation on a request has generated errors, and respond accordingly, but a filter can easily do so.
Based on explanation of this documentation. Both middle ware approach and filter approach will meet your requirements. If you need more information of MVC pipeline and its information of errors, you should use filter approach.
Upvotes: 1