Abd*_*lah 5 design-patterns exception-handling exception
如果应用程序发现用户未经过身份验证/授权执行某项操作,那是否是意外情况?
try {
if (notAuth())
throw new UnAuthException();
} catch (UnAuthException e) {
Log . error(e);
return false;
}
Run Code Online (Sandbox Code Playgroud)
如果是预期的情况,那么为什么有这么多的框架有自己的UnAuthException如果失败的Auth不是例外?
取决于范围。
在业务逻辑层“用户未经授权/验证”的情况是异常的,应该导致运行时异常,例如(Java代码):
public String salutation(User user) {
// may lead to a runtime exception if user is not authorized
return String.format("Hello, %s!", user.getName());
}
Run Code Online (Sandbox Code Playgroud)
的实现User(当然,它是一个接口)将返回用户名或抛出一个NonAuthenticatedExceptionin getName()。
在访问控制层中,用户授权/认证状态被视为任何其他正常状态,并且不应被视为异常情况,例如:
if (!user.isAuthenticated()) {
httpResponse.addHeader("WWW-Authenticate", "Basic realm=\"secure content\"");
}
Run Code Online (Sandbox Code Playgroud)