标签:
1.在@ExceptionHandler 方法的入参中可以加入 Exception 类型的参数, 该参数即对应发生的异常对象直接上实例:
在Controller中:
<span style="font-size:18px;"><span style="font-family:SimSun;font-size:18px;">package com.cgf.springmvc.handlers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; @RequestMapping(value="/springmvc") @Controller public class MyException { <span style="color:#ff0000;">@ExceptionHandler(value={Exception.class})</span> public ModelAndView myException(Exception ex){ ModelAndView mv=new ModelAndView("error"); mv.addObject("exception", ex); return mv; } @RequestMapping(value="/testException") public String testException(@RequestParam(value="id")int id){ System.out.println("id=:"+10/id); return "success"; } }</span></span>在springmvc.xml中:需要配置<mvc:annotation-driven/>
在index.jsp中;
<span style="font-size:18px;"><span style="font-family:SimSun;"> <h1>异常处理</h1> <a href="springmvc/testException?id=1">Test Exception</a> <br></span></span>4.@ControllerAdvice: 如果在当前 Handler 中找不到 @ExceptionHandler 方法来出来当前方法出现的异常,
则将去@ControllerAdvice 标记的类中查找 @ExceptionHandler 标记的方法来处理异常.
<span style="font-size:18px;">package com.cgf.springmvc.handlers; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.ModelAndView; <span style="background-color: rgb(255, 255, 255);"><span style="color:#ff0000;">@ControllerAdvice</span></span> public class MyArithmeticException { @ExceptionHandler(value={ArithmeticException.class}) public ModelAndView myException(Exception ex){ System.out.println("MyArithmeticException"); ModelAndView mv=new ModelAndView("error"); mv.addObject("exception", ex); return mv; } }</span>
5.ResponseStatusExceptionResolver处理用@ResponseStatus标识的异常类或异常方法
<span style="font-family:SimSun;font-size:18px;">package com.cgf.springmvc.handlers; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(reason="用户名与密码不匹配",value=HttpStatus.FORBIDDEN) public class UserNameNotMatchPasswordException extends RuntimeException{ /** * */ private static final long serialVersionUID = 1L; }</span>
标签:
原文地址:http://blog.csdn.net/baidu_21578557/article/details/51512403