springmvc異常處理方式1
1.@ExceptionHandler(ArithmeticException.class)
public ModelAndView getArithmeticException(Exception ex){
ModelAndView mv = new ModelAndView("error");
mv.addObject("ex", ex);
return mv;
}
@RequestMapping("/zero")
public void ac(@RequestParam("i") int i){
System.out.println(10/i);
}
當(dāng)發(fā)生ArithmeticException異常的時(shí)候,在error.jsp頁(yè)面輸出異常 。
2.
@ControllerAdvice
public class Exceptions {
@ExceptionHandler(ArithmeticException.class)
public ModelAndView getArithmeticException(Exception ex){
ModelAndView mv = new ModelAndView("error");
mv.addObject("ex", ex);
return mv;
}
}
如果在本類中找不到異常處理的方法,就去@ControllerAdvice注解的類中查找異常處理的類的方法。
3.
@ResponseStatus(value=HttpStatus.BAD_REQUEST,reason="請(qǐng)求不對(duì)")
public class UserExceptions extends RuntimeException{
/**
*
*/
private static final long serialVersionUID = 1L;
}
在controller的方法里拋出UserExceptions 異常,在頁(yè)面上顯示
HTTP Status 400 - 請(qǐng)求不對(duì)
posted on 2016-07-28 09:49 楊軍威 閱讀(108) 評(píng)論(0) 編輯 收藏