开发者

GWT - Throwing an exception vs returning null

开发者 https://www.devze.com 2023-02-23 12:21 出处:网络
Suppose you have a method like this implemented on server side: @Override public User login(String username, String password) throws AuthenticationFailedException {

Suppose you have a method like this implemented on server side:

@Override
public User login(String username, String password) throws AuthenticationFailedException {
    // obtain hash from user's db entry - omitted to simplify code

    String sessionID = UUID.randomUUID().toString();
    currentlyLoggedIn.put(sessionID, new Session(username));

  开发者_C百科  return new User(sessionID, username);
}

The method takes a username and password, retrieves the password from the database and checks if it is valid. If it is valid, it returns the a User object with a generated sessionID and username. But what if the method fails? Or in general, what would be the best approach if a method does not succeed? Return null, or throw some exception?


Always return an exception. A null can mean whatever, but an exception can have attached a message explaining the reason of the problem. And that's not only applicable to GWT, but to also to Java.

0

精彩评论

暂无评论...
验证码 换一张
取 消