实现接口 HandlerExceptionResolver
所有的异常都会调用
/**
* 自定义全局异常处理器
*/
@Component
public class MyException implements HandlerExceptionResolver {
/**
* 当系统运行时,某一个方法抛出异常,那么该方法就会被触发
*
* @param request 当前请求对象
* @param response 当前响应对象
* @param handler 处理器本身(可以简单理解为接口方法)
* @param ex 抛出的异常对象
* @return 返回值是一个 ModelAndView,也就是要展示的内容
*/
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
//我的异常页面视图是 jsp 目录下的 error.jsp 文件
ModelAndView mv = new ModelAndView("error");
mv.addObject("error", ex.getMessage());
return mv;
}
}
public class MyExResolver implements HandlerExceptionResolver{
/**
* 异常解析器:主体逻辑
* 执行时刻:当handler中抛出异常时,会执行:捕获异常,并可以跳到错误页面
*/
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
ex.printStackTrace();//打印异常栈
//创建一个ModelAndView
ModelAndView mv = new ModelAndView();
//识别异常
if (ex instanceof Exception1) {
mv.setViewName("redirect:/xxx/error1");
}else if(ex instanceof Exception2){
mv.setViewName("redirect:/xxx/error2");
}else{
mv.setViewName("redirect:/xxx/error");
}
return mv;
}
}
通过 @ExceptionHandler 注解定义(推荐)
发生异常时进入对应的异常界面
package com.qfedu.demo.exception;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
/**
* 定义一个全局异常处理类
*
* @ControllerAdvice 表示当前类是一个增强的处理器,也可以理解为这是一个全局的处理器(可以作用于所有controller的处理器)
* <p>
* 所以当前类就相当于是一个 Controller,里边方法的定义,也和普通 controller 方法的定义一样
*/
//@ControllerAdvice
public class MyException02 {
/**
* @param model
* @param e
* @return
* @ExceptionHandler 表示指定异常的类型,即当发生 ArithmeticException 异常的时候,会触发该方法
*/
// @ExceptionHandler(ArithmeticException.class)
// public String arithmeticException(Model model, ArithmeticException e) {
// model.addAttribute("error", e.getMessage());
// return "error";
// }
// @ExceptionHandler(ArithmeticException.class)
// public ModelAndView arithmeticException2(ArithmeticException e) {
// ModelAndView mv = new ModelAndView();
// mv.addObject("error", e.getMessage());
// return mv;
// }
/**
* 发生异常时,返回 json
* @param e
* @return
*/
@ExceptionHandler(ArithmeticException.class)
@ResponseBody
public Map<String,Object> arithmeticException3(ArithmeticException e) {
HashMap<String, Object> map = new HashMap<>();
map.put("error", e.getMessage());
return map;
}
}