2013-08-31 26 views
1

使用異常我已閱讀,使用異常的控制流不好,但我怎麼能實現不拋出異常輕鬆以下?因此,如果用戶輸入已經使用的用戶名,我想在輸入字段旁邊顯示錯誤消息。下面是從我的註冊頁面支持bean代碼:控制流

public String signUp() { 
    User user = new User(username, password, email); 

    try { 
     if (userService.save(user) != null) { 
      // ok 
     } 
     else { 
      // not ok 
     } 
    } 
    catch (UsernameInUseException e) { 
     // notify user that username is already in use 
    } 
    catch (EmailInUseException e) { 
     // notify user that email is already in use 
    } 
    catch (DataAccessException e) { 
     // notify user about db error 
    } 

    return "index"; 
} 

保存我的userService的方法:

@Override 
@Transactional 
public User save(User user) { 
    if (userRepository.findByUsername(user.getUsername()) != null) { 
     LOGGER.debug("Username '{}' is already in use", user.getUsername()); 
     throw new UsernameInUseException(); 
    } 
    else if (userRepository.findByEmail(user.getEmail()) != null) { 
     LOGGER.debug("Email '{}' is already in use", user.getEmail()); 
     throw new EmailInUseException(); 
    } 

    user.setPassword(BCrypt.hashpw(user.getPassword(), BCrypt.gensalt())); 
    user.setRegisteredOn(DateTime.now(DateTimeZone.UTC)); 

    return userRepository.save(user); 
} 
+1

你使用任何框架?或者它只是簡單的基於Servlet-JSP的Web應用程序? –

+0

我使用的是JSF 2.2,Spring 3.2和Hibernate 4.2 – perak

回答

0

使用異常的工作原理是什麼都你這樣做。你可以使用它,但不要過分。

一般來說,你想扔的時候發生了一件事情,這是不對的,但你的程序可以從中恢復,很可能在另一個模塊異常。例外有助於將程序(更確切地說是運行時堆棧)置於良好的狀態,以便您可以對錯誤進行一些處理。

使用返回值通常不是一個好主意,常常被看作是不那麼好的設計。

在你的情況異常將最有可能觸發的信息給用戶,這發生在用戶界面,並應遠離註冊邏輯本身,所以用一個例外似乎是適當的。

現在矯枉過正它的一部分。你可以很容易地做一個例外,例如SignupException,它包含了它出錯的原因。您可能不希望最終產生比具有生產性代碼的類多的異常類。