1. @ExceptionHandler
告诉springmvc这个方法专门处理这个类发生的异常
1.给方法上随便写一个Exception,用来接收发生的异常
2.要携带异常信息不能给参数位置写model
3.返回modelandview
4.如果有多个@ExceptionHandler都能处理这个异常,精确 优先
5.全局异常处理与本类同时存在,本类优先
@Controller
public class ExceptionHandler {
@RequestMapping("/exc01")
public void test() {
int i=10/0;
System.out.println(i);
}
@org.springframework.web.bind.annotation.ExceptionHandler(value= {ArithmeticException.class})
public ModelAndView handler(Exception exception) {
ModelAndView view = new ModelAndView("error");
view.addObject("ex", exception);
return view;
}
<body>
<h1>发生错误了</h1>
${ex }
</body>
2.集中处理所有异常
1.集中处理所有异常的类加入到IOC容器中
2.。@ControllerAdvice专门处理异常的类
3、自定义异常
(前提没有其他异常处理方法)
继承RuntimeException
package com.atguigu.controller;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(reason="用户拒绝登录", value=HttpStatus.NOT_EXTENDED)
public class UserNameNotFoundException extends RuntimeException{
private static final long serialVersionUID = 1L;
}
请求处理
@RequestMapping("/exc02")
public String test2(@RequestParam("username")String username) {
if (!"admin".equals(username)) {
System.out.println("登录失败");
throw new UserNameNotFoundException();
}
System.out.println("登陆成功");
return "/list";
}
、