使用Model addAttribute在UI中进行错误处理

时间:2018-01-27 07:59:56

标签: spring

示例代码

@RequestMapping(value = "/add", method = RequestMethod.POST)
public ModelAndView addEmployee(Model model, EmpTO empTO, BindingResult bindingResult){
    try {
        empService.saveOrUpdateEmployee(empTO);
    } catch (Exception e) {
        if (e instanceof InvException) {
            model.addAttribute("error", ((InvException) e).getError());
        } else {
            model.addAttribute("error", PresentationUtil.handleApplicationRuntimeError(e));
        }
        return new ModelAndView("emp/save");
    }
    empTO = new EmpTO();
    return new ModelAndView("emp/home");
}

的问题:

  1. 以上是正确的方法吗?
  2. 我们可以将错误代码和描述存储在数据库表或硬编码字符串中,让UI处理错误代码吗?
  3. 这是标准的行业惯例吗?
  4. Thank.s

1 个答案:

答案 0 :(得分:0)

我们使用@ExceptionHandler注释,它允许我们处理Controller方法之外的异常。无需将错误代码放在数据库表中。

异常类:

public class InvException extends RuntimeException {
    private String errorCode;
    private String errorMsg;
    //setter/getter
    ...
}

并在控制器中

@RequestMapping(value = "/add", method = RequestMethod.POST)
public ModelAndView addEmployee(Model model, EmpTO empTO, BindingResult bindingResult){
   ...
   } catch (InvException e) {
      throw new InvException("E400", "This is Inv Exception");
   } catch (Exception e) {
       throw new Exception(...);
   }
}

@ExceptionHandler(InvException.class)
public ModelAndView handleMyOwnException(InvException ex) {
    ModelAndView model = new ModelAndView("your specific error view");
    model.addObject("errCode", ex.getErrorCode());
    model.addObject("errMsg", ex.getErrorMsg());
    return model;
}

@ExceptionHandler(Exception.class)
public ModelAndView handleAllException(Exception ex) {
    ModelAndView model = new ModelAndView("your generic error view ");
    model.addObject("errMsg", "There is a exception");
    return model;
}

@ExceptionHandler适用于单个控制器。它可以通过创建一个新类并使用@ControllerAdvice

进行注释来应用于所有控制器
@ControllerAdvice
public class GlobalExceptionController {
    @ExceptionHandler(InvException.class)
    public ModelAndView handleMyOwnException(InvException ex) {...}
    @ExceptionHandler(Exception.class)
    public ModelAndView handleAllException(Exception ex) {...}
}