1.在@ExceptionHandler 方法的入参中可以加入 Exception 类型的参数, 该参数即对应发生的异常对象
[email protected]方法的入参中不能传入 Map.若希望把异常信息传导页面上,需要使用 ModelAndView作为返回值
[email protected] 方法标记的异常有优先级的问题.会先处理匹配度高的异常
直接上实例:
在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>
[email protected]: 如果在当前 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>
时间: 2024-11-05 07:50:01