Mapping .NET exceptions to HTTP status codes

3

Situation

I'm implementing a HttpModule which is responsible for monitoring usage patterns and intercepting and managing unhandled exceptions in ASP.NET applications via events BeginRequest , EndRequest and Error of context current of HttpApplication .

Question

Is there any direct and already implemented way to map exceptions from the .NET platform to its HTTP equivalents? I can imagine that some mappings would be:

FileNotFoundException       > 404 File Not Found
UnauthorizedAccessException > 403 Forbidden
AuthenticationException     > 401 Unauthorized
[...]
(Qualquer outra exceção)  > 500 Internal Server Error

I do not want to reinvent the wheel, and I'd rather use some function already implemented (preferably platform native).

    
asked by anonymous 16.07.2014 / 21:41

1 answer

3

Solution

Exceptions can be cast for the type HttpException , and from this type the GetHttpCode() method can be called:

        try
        {
            throw new FileNotFoundException("Teste");
        }
        catch (Exception err)
        {
            var httpException = err as HttpException;
            if (httpException != null)
            {
                var httperror = httpException.GetHttpCode();
                // O valor de httperror é 404.
            }
        }

Source: link

    
17.07.2014 / 16:17