spring自定义异常:
要自定义异常,可以通过继承runtimeexception来实现,要定义一个异常视图:
通过implements HandlerExceptionResolver来实现:例如:
重写方法:
public class ExceptionHander implements HandlerExceptionResolver{
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object ob,
Exception ex) {
// TODO Auto-generated method stub
Map<String, Object> model = new HashMap<String, Object>();
model.put("ex", ex);
if(ex instanceof NofindException) {
return new ModelAndView("error-business", model);
}else {
return new ModelAndView("error", model);
}
}
}
要说明一下,ModelAndView的这个构造方法:new ModelAndView(String, map) 那个字符串是视图名,后面的map是视图传递的值,根据key取值。
要想给controller中使用,需要做一个基础类,配置@ExceptionHandler,以便通过controller类继承基础这个类,出现异常处理,调用这个方法:
基础类如下:
public class BaseController {
@ExceptionHandler
public String Exception(HttpServletRequest request,Exception ex){
request.setAttribute("ex", ex);
if(ex instanceof NofindException){
return "error-business";
}else{
return "exception";
}
}
}
只需要继承就好了。
这就是spring自定义异常.
可以把ExceptionHander 与BaseController 合二为一,用spring的aop就可以做到:如下
@ControllerAdvice
public class Hander {
@ExceptionHandler(NofindException.class)
public String donotfind(){
return "notfind";
}
@ExceptionHandler(RuntimeException.class)
public String rungtime(){
return "runtimeexception";
}
}
go,go,go