Can app.UseErrorHandler() access error details?

前端 未结 3 776
轻奢々
轻奢々 2021-01-02 11:33

In my MVC4 app I had a global.asax.cs override of Application_Error(object sender, EventArgs e) where I could extract the exception, statusCo

相关标签:
3条回答
  • 2021-01-02 12:12

    From your configured error handling action, you could do something like:

    public IActionResult Error()
    {
        // 'Context' here is of type HttpContext
        var feature = Context.GetFeature<IErrorHandlerFeature>();
        if(feature != null)
        {
            var exception = feature.Error;
        }
    ......
    .......
    
    0 讨论(0)
  • 2021-01-02 12:18

    Aug. 02th 2016 - Update for 1.0.0

    Startup.cs

    using Microsoft.AspNet.Builder;
    
    namespace NS
    {
        public class Startup
        {
             ...
             public virtual void Configure(IApplicationBuilder app)
             {
                 ...
                 app.UseExceptionHandler("/Home/Error");
                 ...
             }
         }
    }
    

    HomeController.cs

    using Microsoft.AspNet.Diagnostics;
    using Microsoft.AspNet.Http.Features;
    using Microsoft.AspNet.Mvc;
    using Microsoft.Extensions.Logging;
    
    namespace NS.Controllers
    {
        public class HomeController : Controller
        {
            static ILogger _logger;
            public HomeController(ILoggerFactory factory)
            {
                if (_logger == null)
                    _logger = factory.Create("Unhandled Error");
            }
    
            public IActionResult Error()
            {
                var feature = HttpContext.Features.Get<IExceptionHandlerFeature>();
                var error = feature?.Error;
                _logger.LogError("Oops!", error);
                return View("~/Views/Shared/Error.cshtml", error);
            }
        }
    }
    

    project.json

    ...
    "dependencies": {
        "Microsoft.AspNet.Diagnostics": "1.0.0",
         ...
    }
    ...
    
    0 讨论(0)
  • 2021-01-02 12:29

    In Beta8, agua from mars' answer is a little different.

    Instead of:

    var feature = Context.GetFeature<IErrorHandlerFeature>();
    

    Use:

    var feature = HttpContext.Features.Get<IExceptionHandlerFeature>();
    

    This also requires a reference to Microsoft.AspNet.Http.Features, and the following line in Configure() in Startup.cs:

    app.UseExceptionHandler("/Home/Error");
    
    0 讨论(0)
提交回复
热议问题