你们可以分享一些关于如何设计一个好的实现来处理Spring MVC异常的建议吗?以下是我在网上花了一些时间试图找出处理异常的合适或更好的实现之后的一些想法。
以下是我正在进行的项目的一些背景知识:
所以,这是我的困惑。我想到了两种类型的异常处理机制。两者都是使用@ControllerAdvice实现的,它将单独的Java类中的异常处理分开。
方法A.
方法B.
所以,这些是我现在面临的问题。我希望我在处理Spring Web异常方面朝着正确的方向前进。请让我知道你的想法。谢谢。
例:
让我们使用帐户注册方法作为示例:
//In the controller class
public String accountSignUp(@Valid AccountSignUpForm form){
if(bindingResult.hasErrors()){
return "signupview";
}
accountSignUpSvc.validateEmail(form.getEmail);
accountSignUpSvc.createAccount(form);
}
// In the accountSignUpSvc class;
public interface AccountSignUpSvc {
// Check if email has been used for sign up.
void validateEmail(String email) throws DuplicateAccountException;
// Create the account based on the form.
void createAccount(AccountSignUpForm form) throws AccountCreationException;
}
所以使用方法A:
//In the controller class
public String accountSignUp(@Valid AccountSignUpForm form){
if(bindingResult.hasErrors()){
return "signupview";
}
try{
accountSignUpSvc.validateEmail(form.getEmail);
} catch ( DuplicateAccountException e){
// Rethrow with a controller method specific exception
throw new AccountSignUpException("Returned error message"," Internal error message.",e);
}
// Then implement the similar try catch block for the accountSignUpSvc.createAccount method
}
@ControllerAdvice
public class AccountSignUpExceptionHandler{
@ExceptionHandler(AccountSignUpException.class)
public ModelAndView handleAccountSignUpException(HttpServletRequest request, AccountSignUpException ex){
log.error(ex.getInternalError);
ModelAndView mav = new ModelAndView("signup");
mav.addObject("returnError", ex.getReturnError());
return mav;
}
然后使用方法B:
//In the controller class
public String accountSignUp(@Valid AccountSignUpForm form){
if(bindingResult.hasErrors()){
return "signupview";
}
accountSignUpSvc.validateEmail(form.getEmail);
// Then implement the similar try catch block for the accountSignUpSvc.createAccount method
}
@ControllerAdvice
public class AccountSignUpExceptionHandler{
@ExceptionHandler(DuplicateAccountException.class)
public ModelAndView handleDuplicateAccountException(HttpServletRequest request, DuplicateAccountException ex){
log.error("Error due to error");
ModelAndView mav = new ModelAndView("signup");
mav.addObject("returnError", "Return error message: a long error message.");
return mav;
}
我提到的好处是异常处理程序可以是特定的,因为只有某个条件会触发它。因此,应该在html页面上显示的任何长返回消息都可以在此特定异常处理程序中进行编码。
在我看来,这取决于你所讨论的这些例外是否是经过检查的例外情况。如果它们都是在methodA()中抛出的所有检查异常,那么我倾向于使用方法A并捕获这些异常并将它们作为您自己的应用程序特定异常返回,并在@ControllerAdvice类中使用单个处理程序。
但是,如果您想要处理应用程序中可能出现的未经检查的异常的错误响应,那么我将使用方法B.
对于异常唯一字段:
try{
}
catch(DataIntegrityViolationException e)
{
}