There is a global exception handler in our WebAPI application that looks like the following:
public class ApiExceptionHandler : IExceptionHandler
{
public async Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
{
var exceptionType = context.Exception.GetType();
if (exceptionType == typeof(ResourceNotFoundException))
{
context.Result = new ResponseMessageResult(
context.Request.CreateResponse(HttpStatusCode.NotFound, context.Exception.Message));
}
else if (exceptionType == typeof(UserNotFoundException))
{
context.Result = new ResponseMessageResult(
context.Request.CreateResponse(HttpStatusCode.Unauthorized, context.Exception.Message));
}
else if (exceptionType == typeof(UserAlreadyExistsExeption))
{
context.Result = new ResponseMessageResult(
context.Request.CreateResponse(HttpStatusCode.Conflict, context.Exception.Message));
}
...
else
{
context.Result = new ResponseMessageResult(
context.Request.CreateResponse(HttpStatusCode.InternalServerError, "An unexpected error occured"));
}
}
}
And each exception has the following form:
public class UserAlreadyExistsExeption: Exception
{
public UserAlreadyExistsExeption()
{
}
public UserAlreadyExistsExeption(string message) : base(message)
{
}
public UserAlreadyExistsExeption(string message, Exception inner) : base(message, inner)
{
}
}
And can be thrown in the code like the following:
//If user exists
throw new UserAlreadyExistsExeption("User already exists");
I was thinking of making all our custom exceptions implement a IHasHttpErrorCode so each one has its own HttpErrorCode - usage like the following:
Interface:
public interface IHasHttpErrorCode
{
HttpStatusCode GetHttpStatusCode();
}
Exception:
public class UserAlreadyExistsExeption: Exception, IHasHttpErrorCode
{
public UserAlreadyExistsExeption()
{
}
public UserAlreadyExistsExeption(string message) : base(message)
{
}
public UserAlreadyExistsExeption(string message, Exception inner) : base(message, inner)
{
}
public HttpStatusCode GetHttpStatusCode() {
return HttpStatusCode.Conflict;
}
}
Global Error Handler:
public class ApiExceptionHandler : IExceptionHandler
{
public async Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
{
var exceptionType = context.Exception as IHasHttpErrorCode;
if (customException != null) {
context.Result = new ResponseMessageResult(
context.Request.CreateResponse(customException.GetHttpStatusCode(), context.Exception.Message));
}
else
{
context.Result = new ResponseMessageResult(
context.Request.CreateResponse(HttpStatusCode.InternalServerError, "An unexpected error occured"));
}
}
}
Is this a valid approach to improve the existing code? Is there anything else I should look to improve?