SpringBoot中两种处理异常的方式
本篇介绍一下SpringBoot中两种处理异常的方式
一、实现ErrorPageRegistrar接口,指定跳转页面
1、实现ErrorPageRegistrar接口
@Component public class CommonErrorPageRegistrar implements ErrorPageRegistrar { @Override public void registerErrorPages(ErrorPageRegistry registry) { ErrorPage e404=new ErrorPage(HttpStatus.NOT_FOUND,"/404.html"); ErrorPage e500=new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR,"/500.html"); ErrorPage args=new ErrorPage(IllegalArgumentException.class,"/args.html"); ErrorPage nullpoint=new ErrorPage(NullPointerException.class,"/nullpoint.html"); registry.addErrorPages(e404,e500,args,nullpoint); } }
2、在resources/public下建异常页面
3、编写测试类
@RestController public class UserController { @RequestMapping("/user/innererror") public String innererror(){ int a=10/0; return "innererror"; } @RequestMapping("/user/index") public String index(){ throw new IllegalArgumentException("IllegalArgumentException抛出的异常"); } @RequestMapping("/user/empty") public String empty(){ throw new NullPointerException("NullPointerException抛出的异常"); } }
测试:浏览器输入与跳转关系如下
http://localhost:8080/user/aaa 跳转404.html
http://localhost:8080/user/innererror 跳转500.html
http://localhost:8080/user/index 跳转args.html
http://localhost:8080/user/empty 跳转nullpoint.html
二、使用注解的方式捕获满足其参数(异常类)的异常
1、ExceptionHandler注解,用在类的方法上,只处理本类中的异常
@RestController public class BookController { @ExceptionHandler(value=Exception.class) public String error(Exception e){ return "found exception:"+e.getMessage(); } @RequestMapping("/book/error1") public String error1 () throws FileNotFoundException{ throw new FileNotFoundException(" book.txt not found"); } @RequestMapping("/book/error2") public String error2 () throws ClassNotFoundException{ throw new ClassNotFoundException(" Book class not found"); } }
@RestController public class UserController { @RequestMapping("/user/index") public String index(){ throw new IllegalArgumentException("IllegalArgumentException抛出的异常"); } }
测试:浏览器输入与输出关系如下
http://localhost:8080/book/error1 输出:found exception: book.txt not found
http://localhost:8080/book/error2 输出:found exception: Book class not found
http://localhost:8080/user/index 输出:Whitelabel Error Page(SpringBoot默认的)
由于UserController中没有定义ExceptionHandler,所有会使用SpringBoot默认的异常
2、ControllerAdvice注解,用在类上,处理所有Controller里面的异常
将处理异常的方法提取到一个类中,异常发生时优先匹配本类中的方法,本类中无法找到则取匹配全局(使用ControllerAdvice)的
@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(value=Exception.class) @ResponseBody public String error(Exception e){ return "global exception:"+e.getClass().getName(); } }
此时输入http://localhost:8080/user/index,页面输出global exception:java.lang.IllegalArgumentException
如果一个工程中即使用了页面,也使用了注解的方式,使用注解方式的优先级别更高