SpringMVC异常处理方式二:自定义异常处理类
创建一个自定义异常处理类,其中的每一个方法就处理全局范围内的一个异常
MyExceptionResolver
异常处理类
package com.bb.exception;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
/**
* 实现异常处理和controller分离
* @author Administrator
*
*/
@ControllerAdvice
@Component
public class MyExceptionResolver {
/**
* 当出现空指针异常的时候处理
* @return
*/
@ExceptionHandler(value={NullPointerException.class})
public ModelAndView resovlerNullPointerException(){
System.out.println("111111111111");
ModelAndView mm = new ModelAndView();
mm.setViewName("/error.jsp");
mm.addObject("msg", "空指针异常");
return mm;
}
/**
* 当出现空指针异常的时候处理
* @return
*/
@ExceptionHandler(value={ArithmeticException.class})
public ModelAndView resovlerArithmeticException(){
System.out.println("22222222222222");
ModelAndView mm = new ModelAndView();
mm.setViewName("/error.jsp");
mm.addObject("msg", "计算异常...");
return mm;
}
}
测试 control
类
package com.bb.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class UserController {
@RequestMapping("/query1")
public String query1(Integer num) throws NullPointerException {
System.out.println("query1....");
if(num == 1){
// 我们抛出一个异常信息
throw new NullPointerException();
}
return "user.jsp";
}
@RequestMapping("/query2")
public String query2(Integer num) throws ArithmeticException{
System.out.println("query2....");
if(num == 1){
// 我们抛出一个异常信息
throw new ArithmeticException();
}
return "user.jsp";
}
/**
* 当出现空指针异常的时候处理
* @return
*/
@ExceptionHandler(value={NullPointerException.class})
public ModelAndView resovlerNullPointerException(){
ModelAndView mm = new ModelAndView();
mm.setViewName("/error.jsp");
mm.addObject("msg", "空指针异常");
return mm;
}
/**
* 当出现空指针异常的时候处理
* @return
*/
@ExceptionHandler(value={ArithmeticException.class})
public ModelAndView resovlerArithmeticException(){
ModelAndView mm = new ModelAndView();
mm.setViewName("/error.jsp");
mm.addObject("msg", "计算异常...");
return mm;
}
}
测试截图
项目打包 提取码:7oo4
环境:eclipse