简体   繁体   English

如何在ASP.NET Core中进行异常处理?

[英]How to do exception handling in asp.net core?

I have to do the exception handling in asp.net core I have read so many articles and I have implemented it on my startup.cs file here is the code 我必须在asp.net核心中执行异常处理,我已经阅读了很多文章,并且已经在我的startup.cs文件中实现了这是代码

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider svp)
    {
        app.UseExceptionHandler(errorApp =>
        {
            errorApp.Run(async context =>
            {
                context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; ; // or another Status accordingly to Exception Type
                context.Response.ContentType = "application/json";

                var error = context.Features.Get<IExceptionHandlerFeature>();
                if (error != null)
                {
                    var ex = error.Error;

                    await context.Response.WriteAsync(new ErrorDto()
                    {
                        Code = 1,
                        Message = ex.Message // or your custom message
                        // other custom data
                    }.ToString(), Encoding.UTF8);
                }
            });
            app.UseMvc();

I am having a problem that how to call this code when there is exception occur in my controller. 我有一个问题,就是在控制器中发生异常时如何调用此代码。

I will be very thankfullk to you. 我将非常感谢您。

Here is the controller code-: 这是控制器代码:

[HttpPost]
    [AllowAnonymous]
    public async Task<JsonResult> Register([FromBody] RegisterViewModel model)
    {
        int count = 1;
        int output = count / 0;
        var user = new ApplicationUser { UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, UserType = model.UserType };
        user.FirstName = user.UserType.Equals(Models.Entity.Constant.RECOVERY_CENTER) ? model.Name : model.FirstName;
        var result = await _userManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
            // Send an email with this link
            //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
            //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
            //await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
            //    $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");
            await _signInManager.SignInAsync(user, isPersistent: false);
            _logger.LogInformation(3, "User created a new account with password.");
            user = await _userManager.FindByEmailAsync(user.Email);
            var InsertR = await RecoveryGuidance.Models.Entity.CenterGateWay.AddNewRecoveryCenter(new Models.Entity.Center { Rec_Email = user.Email, Rec_Name = user.FirstName, Rec_UserId = user.Id });
        }
        AddErrors(result);
        return Json(result);

    }

You don't need to call it. 您不需要调用它。 UseExceptionHandler is an extension method which uses ExceptionHandlerMiddleware . UseExceptionHandler是使用ExceptionHandlerMiddleware的扩展方法。 See middleware source code : 参见中间件源代码

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next(context);// action execution occurs in try block
        }
        catch (Exception ex)
        {
           // if any middleware has an exception(includes mvc action) handle it
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM