Exception mapping . NET for HTTP status codes

Asked

Viewed 92 times

3

Situation

I’m working on one Httpmodule who is responsible for monitoring usage patterns and intercepting and managing untreated exceptions in ASP.NET applications via events BeginRequest, EndRequest and Error of the current context of HttpApplication.

Question

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

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

I don’t want to reinvent the wheel, and prefer to use some function already implemented (preferably native to the platform).

  • Its system is ASP.NET MVC?

  • @Gypsy omorrisonmendez Actually no, Morrison - the current implementation is completely agnostic, Saas.

  • Well, if I followed the MVC pattern I had a quick response.

1 answer

3


Solution

Exceptions may suffer cast for the guy HttpException, and from this type the method GetHttpCode() may 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: https://stackoverflow.com/questions/619895/how-can-i-properly-handle-404-in-asp-net-mvc

  • 1

    Considering that you used a link talking about ASP.NET MVC, the answer I was going to suggest was to take advantage of a virtual event implementing the Controller called OnException. There you can get the exception context and raise a more generic message.

  • 1

    @Yes, I would say that the way you mentioned it would work perfectly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.