我正在嘗試處理存在違反唯一欄位(例如,用戶名/郵件)的用例,這樣處理是否正確?(我在dao層使用jdbcInsert)
@Transactional
@Override
public User register(String name, String surname, String username, String email, String password) {
User user = null;
try {
user = userDao.register(name, surname, username,
email, passwordEncoder.encode(password));
} catch (DuplicateKeyException duplicateKeyException) {
throw new DuplicateUserException(duplicateKeyException.getMessage());
} catch (DataAccessException dataAccessException) {
throw new SystemUnavailableException(dataAccessException.getMessage());
}
return user;
}
并在控制器中捕獲我的自定義例外:
@ControllerAdvice
public class ErrorControllerAdvice {
@ExceptionHandler(DuplicateUserException.class)
public ModelAndView keyViolation(DuplicateUserException ex) {
ModelAndView mav = new ModelAndView("admin/user/new");
mav.addObject("duplicateMessage", ex.getErrorMessage());
return mav;
}
@ExceptionHandler(SystemUnavailableException.class)
@ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
public ModelAndView unexpectedDatabaseError(SystemUnavailableException ex) {
LOGGER.error(ex.getErrorMessage());
return new ModelAndView("500");
}
}
uj5u.com熱心網友回復:
對我來說看起來不錯。您的自定義例外存在于不同的抽象級別,這為它們提供了存在的充分理由。
不過,您可能會考慮在控制器中處理例外,而不是使用 Error 轉換器類 ( ErrorControllerAdvice)。這使事情變得更加明確,并限制了有關如何處理例外的意外情況。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/321975.html
上一篇:SpringwithJackson全域設定JsonAutoDetect
下一篇:可以忽略類路徑上的配置類嗎?
