3

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

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

    }
2
  • 1
    Normally I do a mix of both middleware and a global IExceptionFilter for that. The filter handle controller errors directly and I use the middleware one for a more "low level" handling. As a hint, if you have a need to run code depending of exception type, feel free to use a small library I made: medium.com/@nogravity00/… Commented Feb 17, 2017 at 19:40
  • Found example definition of AddErrors here: tektutorialshub.com/asp-net-core/asp-net-core-identity-tutorial private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } Commented Apr 9, 2019 at 1:49

1 Answer 1

4

You don't need to call it. UseExceptionHandler is an extension method which uses 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
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.