在多层 spring 项目中抛出自定义异常
Throwing custom exceptions in multi-layered spring project
我正在尝试处理违反唯一字段(例如,username/mail)的用例,这样处理是否正确? (我在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");
}
}
我觉得不错。您的自定义异常处于不同的抽象级别,这为它们的存在提供了充分的理由。
您可以考虑在控制器中处理异常,而不是使用错误转换器 class (ErrorControllerAdvice
)。这使事情变得更加明确,并限制了异常处理方式的意外。
我正在尝试处理违反唯一字段(例如,username/mail)的用例,这样处理是否正确? (我在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");
}
}
我觉得不错。您的自定义异常处于不同的抽象级别,这为它们的存在提供了充分的理由。
您可以考虑在控制器中处理异常,而不是使用错误转换器 class (ErrorControllerAdvice
)。这使事情变得更加明确,并限制了异常处理方式的意外。