目录
全局异常处理类
package com.exceptionHandle.exception;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import javax.jws.WebParam;
//全局异常处理类ControllerAdvice,可以捕获到controller里所有异常
@ControllerAdvice
public class MyExceptionHandle{
@ExceptionHandler(IndexOutOfBoundsException.class)
public String exception1(Exception ex, Model model){
model.addAttribute("message",ex.getMessage()+"指针超出异常");
//返回自定义的友好页面
return "error.jsp";
}
@ExceptionHandler(NullPointerException.class)
public String exception2(Exception ex, Model model){
model.addAttribute("message",ex.getMessage()+"空指针异常");
return "error.jsp";
}
@ExceptionHandler(MyException1.class)
public String exception3(Exception ex, Model model){
model.addAttribute("message",ex.getMessage()+"exception1自定义异常");
return "error.jsp";
}
@ExceptionHandler(Exception.class)
public String exception4(Exception ex, Model model){
model.addAttribute("message",ex.getMessage()+"异常");
return "error.jsp";
}
}
全局异常处理类ControllerAdvice,可以捕获到controller里所有异常
@ControllerAdvice
@ExceptionHandler(IndexOutOfBoundsException.class)
当一个方法使用 @ExceptionHandler
注解时,它会被当作一个特殊的异常处理器,用于处理其他控制器方法抛出的异常。
参数为指定异常类,会自动捕获所有给类型的异常进行处理。
控制器
package com.exceptionHandle.controller;
import com.exceptionHandle.exception.MyException1;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class ErrorController {
//IndexOutOfBoundsException
@RequestMapping("error1")
public String error1(){
int[] ints = new int[3];
ints[0]=1;
ints[1]=2;
ints[2]=3;
ints[3]=4;
return "error1";
}
//NullPointerException
@RequestMapping("error2")
public String error2(){
String s= null;
System.out.println(s.length());
return "error2";
}
@RequestMapping("error3")
public String error3(){
int i=1/0;
return "error2";
}
//自定义异常MyException1.class
@RequestMapping("error4")
public String error4() throws MyException1 {
throw new MyException1("自定义异常");
// return "error2";
}
}
自定义异常
package com.exceptionHandle.exception;
import org.springframework.stereotype.Component;
public class MyException1 extends Exception{
public MyException1(String message){
super(message);
}
}
全局异常处理器处理自定义异常
@ExceptionHandler(MyException1.class)
public String exception3(Exception ex, Model model){
model.addAttribute("message",ex.getMessage()+"exception1自定义异常");
return "error.jsp";
}
控制器抛出自定义异常
//自定义异常MyException1.class
@RequestMapping("error4")
public String error4() throws MyException1 {
throw new MyException1("自定义异常");
// return "error2";
}