If the application found that a user is not authenticated/authorized to do something, Is that an unexpected thing?
try {
if (notAuth())
throw new UnAuthException();
} catch (UnAuthException e) {
Log . error(e);
return false;
}
if it is expected case , so why there are so many frameworks have their own UnAuthException
if failed Auth is not exception ?
But yes global exception handler are sometime important to use where our application scope is too big and on every exception we just need to show user a simple error message. It will save your development time and also reduce code.
Don't Overuse the “Try-Catch” However, one of the common mistakes developers make is to overuse exception handling. Sometimes we do it to keep the code look consistent across different files and methods. But, unfortunately, these would cause adverse effects both for application performance and error detection.
Exception handling is a programming concept that allows an application to respond to different error states (like network down, or database connection failed, etc) in various ways. Handling exceptions and errors correctly is critical to making your code reliable and secure.
Depends on scope.
In business logic layer "user is not authorized/authenticated" situation is exceptional, and should lead to runtime exception, 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());
}
Implementation of User
(it's an interface, of course) will either return user's name or throw a NonAuthenticatedException
in getName()
.
In access control layer user authorization/authentication status is processed as any other normal statuses, and should not be treated as exceptional situation, e.g.:
if (!user.isAuthenticated()) {
httpResponse.addHeader("WWW-Authenticate", "Basic realm=\"secure content\"");
}
Yes, it is a good practice to handle authentication\authorizations via exceptions because :
1) An exception is an anomalous situation that the system does not like and hence through exception handling we are reacting to that situation. Authentication and Authorization exceptions are basically security violations i.e system anomalies, and it is a good practice to to respond to violations. Exception handling framework is a popular mechanism to report violations\system anomalies and hence we use this framework to react to such situations.
That is why all popular frameworks(including .NET) have Auth. exception classes to encapsulate errors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With