Throw 401, want to see browser 401 page, not ASP.NET uncaught exception page

I’m building an extension of the virtual file system that makes sure the user is authenticated to servicestack before serving the file, otherwise I want to throw a 401 error. This is working well except that error page is the ASP.NET “uncaught exception” page, I want to display the browser default 401 page instead.

public class AuthenticatedFileSystemMapping : FileSystemMapping
        public AuthenticatedFileSystemMapping(string alias, string rootDirectoryPath) : base(alias, rootDirectoryPath) 
        { }

        public override IVirtualFile GetFile(string virtualPath)
            //bad kitty if not authenticated
            var req = HostContext.GetCurrentRequest();
            if (!req.IsAuthenticated())
                throw new HttpError(401, nameof(HttpStatusCode.Unauthorized), ErrorMessages.NotAuthenticated.Localize(req));

            return base.GetFile(virtualPath);

The handler that uses that API would need to handle it, which is typically too late by then as the HttpHandler that handles the request has already been decided, e.g. if StaticFileHandler was handling it.

You could choose to return null in your VFS provider so it returns a 404, which is common approach to handle non-authenticated requests to prevent information leakage, e.g. GitHub will return a 404 when trying to access a private repo you don’t have access to.

Alternatively you could use a pre-request filter to short-circuit requests for the protected alias if they’re not authenticated, e.g:

this.PreRequestFilters.Add((req,res) => 
    if (req.PathInfo.StartsWith(alias) && !req.IsAuthenticated()) 
        res.StatusCode = (int)HttpStatusCode.Unauthorized;
        res.StatusDescription = ErrorMessages.NotAuthenticated.Localize(req);