Asp.Net Core API Custom Exception Handler

Exception Handling is important to handle any type of system errors, some known /unknown errors.

Usually when we deal with code we will throw an exception in try-catch block to catch exceptions

Like below we throw the exception

try {

//code

} catch(Exception ex) {

// do semthig with exception

}

When exception occurs, we see stack trace for the exception . sometimes the exception contains lot of unncessary information which looks bit confusing and the exception wont be structured

We need to make sure every exception is handled and error response and data is handled correctly

.Net core has its own native error handling. we can also build our own custom exception handler to catch and handling the errors. This custom one will listen to all request and responses

We will be enabling this middleware exception handler before all usage calls

I created custom HttpException, ErrorResponse and ExceptionHandlerExtension for handling exceptions

Now, i created custom exception handler

Now, call this expcetion handler from startup configure method and use it as first call

app.UseApiExceptionHandler();

Now, throw an exception in code

and run in postman and you can see a proper response as:

If you throw without custom exception you see the message “an unexpected error occured.” with statuscode 500

By throwing proper custom exception with proper status code it will help us to find any issue.

Code in my Github: https://github.com/pbndru/Phani.ExceptionHandler.Api

Leave a comment