How to throw Custom Exceptions in ASP.NET Core Web API

We can handle our errors/exceptions by simply using try-catch blocks. But What if we have to throw custom exceptions on some error. To achieve this custom exception throw approach follow the below-mentioned tutorial.

Custom exception handling and throwing custom exceptions is very important to maintain a standard Web Application. It will create a difference and your code will look more clean and standard. In this post, we are going to learn that how can we throw custom exceptions in our ASP.NET Core Web API project.

 Tools:

Visual Studio Community 2019

Windows OS

Let’s get started:

If we have to throw a custom exception on some error, Like we have to throw a custom exception in response to signup API if we do not receive a strong password according to our requirement. To implement this we have to create a class that we can use to throw our exception response.

public class MyExceptionResponse
    {
        public string Type { get; set; }
        public string Message { get; set; }
        public string StackTrace { get; set; }
        public bool Status { get; set; }
        public int StatusCode { get; set; }
	
        public MyExceptionResponse(Exception ex)
        {
            Type = ex.GetType().Name;
            Message = ex.Message;
            Status = false;
            StackTrace = ex.ToString();
            StatusCode = 500;
            if (ex is HttpStatusException httpException)
            {
                //this.StatusCode = httpException.Status.ToString();
                this.StatusCode = (int)httpException.Status;
            }
        }
        public class HttpStatusException : Exception
        {
            public HttpStatusCode Status { get; set; }
            public HttpStatusException(HttpStatusCode code, string msg) : base(msg)
            {
                this.Status = code;
            }
        }
    }

This is the class that we will use to throw our all exceptions globally. In this class, we can see we have another class that we will use to throw custom exceptions on our custom login and wherever we want to throw a custom error in response. We are deriving this class from our main “Exception” class. Now we have to create a controller that will convert our error exceptions to above mentioned

“MyExceptionResponse.cs” class.

[ApiController]
[ApiExplorerSettings(IgnoreApi = true)]
    public class ExceptionController : ControllerBase
    {
        [Route("exception")]
        public MyExceptionResponse Error()
        {
            var context = HttpContext.Features.Get<IExceptionHandlerFeature>();
            var exception = context?.Error; // Your exception
            var code = 500; // Internal Server Error by default
            
            if (exception is HttpStatusException httpException)
            {
                code = (int)httpException.Status;
            }

            Response.StatusCode = code;

            return new MyExceptionResponse(exception); // Your error model
        }
    } 

Add this into your “startup.cs” at the top of the middleware list.

app.UseExceptionHandler("/exception"); 

After adding this controller into our “Startup.cs” as a middleware so whenever any exception will occur in the project. This exception controller will be called automatically from the middleware pipeline.

Now let’s see how we can throw and handle custom exceptions. This is our custom logic where we want to handle and throw a custom exception.

var passwordValidator = new PasswordValidator<ApplicationUser>();
var valid = await passwordValidator.ValidateAsync(_userManager, null, user.Password);
if(!valid.Succeeded)
throw new HttpStatusException(System.Net.HttpStatusCode.UnprocessableEntity, valid.Errors.FirstOrDefault().ToString());

You can also send a custom message in the exception by adding a string into your exception like this.

var passwordValidator = new PasswordValidator<ApplicationUser>();
var valid = await passwordValidator.ValidateAsync(_userManager, null, user.Password);
if(!valid.Succeeded)
throw new 
HttpStatusException(System.Net.HttpStatusCode.UnprocessableEntity, "Passwords must have at least one uppercase ('A'-'Z'), one digit ('0'-'9') and one non alphanumeric character.") 

So if we have a list of errors and want to send all errors to the user interface we will add a custom string summing up all the errors.

Now let our error/exception on this logic.

throw Custom Exceptions

You can see the type, our custom message, status, and status code as well.

Conclusion:

This is a standard and quality way to handle custom exceptions in ASP.NET Core Web API Project. Try this tutorial and if you do not understand anything or face any issue while applying this method. Do not hesitate to comment below. MYCODEBIT team will try to respond ASAP.

Leave a Reply

Your email address will not be published.