Gaui
Gaui

Reputation: 8959

Handle exceptions / HTTP status code based on exception types

I'm trying to throw some exception, catch it in a HandleException attribute and return it properly to the client.

Here is an example:

[HandleException(Type = typeof(UserNotFoundException), Status = HttpStatusCode.NotFound)]
[HandleException(Type = typeof(LoginFailedException), Status = HttpStatusCode.Unauthorized)]
public UserProfile Login(UserCredentials userCred)

In my Login() function I either throw a UserNotFoundException or LoginFailedException.

My HandleExceptionAttribute looks like this:

public class HandleExceptionAttribute : ExceptionFilterAttribute
{
    public Type Type { get; set; }
    public HttpStatusCode Status { get; set; }

    public override void OnException(HttpActionExecutedContext context)
    {
        var ex = context.Exception;

        ResponseHelper.CreateException(Status, ex.Message);
    }
}

What I want is to be able to handle what kind of exceptions is going to be thrown and handle it properly in an attribute, where I specify the HttpStatusCode.

The problem, with this code, is that the top-most attribute is always called. So even if the exception is a LoginFailedException I always get UserNotFoundException and 404 code returned to the client.

How can I achieve this?

Upvotes: 1

Views: 1088

Answers (1)

Ann L.
Ann L.

Reputation: 13975

Just off the top of my head, it looks like you're going to need to do some filtering in your OnException method, so that you verify that the exception you got matches the exception you intended that instance of the attribute to handle.

public override void OnException(HttpActionExecutedContext context)
{
    var ex = context.Exception;
    if(typeof(ex) == Type)        
        ResponseHelper.CreateException(Status, ex.Message);
}

Upvotes: 2

Related Questions