Is it good practice to handle authentication / authorization errors using exceptions?

If the application detects that the user is not authenticated / authorized to do anything, is this an unexpected thing?

try {
    if (notAuth())
        throw new UnAuthException();
} catch (UnAuthException e) {
    Log . error(e);
    return false;
}

if this is the expected case , so why do so many frameworks have their own UnAuthExceptionif Auth crashes are no exception?

+5
source share
2 answers

Depends on the scope.

In the business logic word “user is not authorized / authenticated”, the situation is exceptional and should lead to an exception of the runtime, for example (Java code):

public String salutation(User user) {
  // may lead to a runtime exception if user is not authorized
  return String.format("Hello, %s!", user.getName());
}

User (, , ) , NonAuthenticatedException getName().

/ , :

if (!user.isAuthenticated()) {
  httpResponse.addHeader("WWW-Authenticate", "Basic realm=\"secure content\"");
}
+4

, \ , :

1) , , , . . I.e , . \ , .

( .NET) Auth. .

+1

All Articles