Reputation: 1020
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);
}
Upvotes: 2
Views: 4635
Reputation: 24063
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
}
}
Upvotes: 4