Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# What exception should I raise here?

Tags:

c#

exception

[WebService(Namespace = "http://service.site.com/service/news")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
[ScriptService]
public class NewsService : System.Web.Services.WebService
{
    [WebMethod]
    [ScriptMethod]
    public void DoPost(string title, string markdown, int categoryId)
    {
        if (!MembershipHelper.IsAtLeast(RoleName.Administrator))
            throw new AuthenticationException();

        // ...
    }
}

There are quite a few options available but none seem to be particularly designed for cases like this.

i.e:

  • UnauthorizedAccessException: I/O
  • AccessViolationException: Memory stuff
  • SecurityAccessDeniedException: Represents the security exception that is thrown when a security authorization request fails.

etc.

Should I create my own type of exception for this? What exception should be raised when membership users don't have enough priviledges to invoke a method?

like image 720
bevacqua Avatar asked Sep 10 '11 16:09

bevacqua


2 Answers

AccessViolationException is a bad idea. It should only be thrown by the runtime itself. And it indicates a very severe failure(Your memory got corrupted) where the only appropriate response is terminating the process. An invalid web request is certainly not equivalent to corrupted memory.

UnauthorizedAccessException sounds like a decent choice. You might want to derive your own class from it to create a more specific exception.

like image 73
CodesInChaos Avatar answered Sep 30 '22 02:09

CodesInChaos


UnauthorizedAccessException seems adequate; it's not reserved for IO operations. But if you don't like it, just create your own.

like image 31
Thomas Levesque Avatar answered Sep 30 '22 02:09

Thomas Levesque