您的位置:首页 > 编程语言 > Java开发

SpringMVC(三)异常处理

2017-08-25 10:08 176 查看
一、在Controller内处理局部异常

 

@ExceptionHandler(value={ArithmeticException.class})
public ModelAndView handlExecution(Exception ex){
ModelAndView  mView=new ModelAndView();
mView.setViewName("error");
mView.addObject("exception",ex);
System.out.println("Controller内部异常处理");
return mView;
}
@RequestMapping("/testExection")
public String testExection(@RequestParam(value="id") Integer id){
System.out.println(10/id);
return "success";
}


 

二、处理全局异常---------定义一个异常处理了(官网:www.fhadmin.org)

package com.neuedu.springmvc.execption;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/*
* 项目名称:springmvc-03
* @author:wzc
* @date 创建时间:2017年8月24日 下午3:31:09
* @Description:处理全局异常的类
* @parameter   (官网:www.fhadmin.org)
*   */
@ControllerAdvice
public class MyExcption {
@ExceptionHandler(value={ArithmeticException.class})
public String handlExecution(Exception ex){
return "error";
}
}


 

条件:

1.加上<mvc:annotation-driven>标签:

2.在当前Handler中定义由@ExceptionHandler注解修饰的方法,用于处理异常信息!

注意:

1.@ExceptionHandler方法修饰的入参中可以加入Exception类型的参数,该参数即对应发生的异常信息

2.@ExceptionHandler方法的入参中不能传入Map.若希望把异常信息传到页面上,需要使用ModelAndView作为方法的返回值。

3.@ExceptionHandler 注解定义的方法优先级问题:

例如发生的是NullPointerException,但是声明的异常有 RuntimeException 和 Exception,

此候会根据异常的最近 继承关系找到继承深度最浅的那个 @ExceptionHandler 注解方法,即标记了 RuntimeException 的方法

4.ExceptionHandlerMethodResolver 内部若找不 到@ExceptionHandler 注解的话,会找@ControllerAdvice 中的@ExceptionHandler 注解方法

 

三、在配置中配置异常处理

 

<!-- 配置异常处理 -->

<!-- 配置异常处理 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!-- 处理的错误异常类型,以及跳转的页面 -->
<prop key="java.lang.ArithmeticException">error</prop>
</props>
</property>
</bean>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  SpringMVC异常处理