spring 自定义异常

         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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值