Как сделать обработку исключений в asp.net ядро?


Я должен сделать обработку исключений в asp.net ядро я прочитал так много статей, и я реализовал его на своем стартапе.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();

У меня возникла проблема, как вызвать этот код, когда в моем контроллере возникает исключение.

Я буду очень thankfullk для вас.

Вот код контроллера -:

[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);

    }
1 2

1 ответ:

Вам не нужно его вызывать. UseExceptionHandler - это метод расширения, который использует ExceptionHandlerMiddleware. Смотрите раздел промежуточное по исходный код:

    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
        }
    }