章节
- Spring Boot 介绍
- Spring Boot 开发环境搭建(Eclipse)
- Spring Boot Hello World (restful接口)例子
- spring boot 连接Mysql
- spring boot配置druid连接池连接mysql
- spring boot集成mybatis(1)
- spring boot集成mybatis(2) – 使用pagehelper实现分页
- spring boot集成mybatis(3) – mybatis generator 配置
- spring boot 接口返回值封装
- spring boot输入数据校验(validation)
- spring boot rest 接口集成 spring security(1) – 最简配置
- spring boot rest 接口集成 spring security(2) – JWT配置
- spring boot 异常(exception)处理
- spring boot 环境配置(profile)切换
- spring boot redis 缓存(cache)集成
概述
异常处理注解
spring中处理异常可以通过2个注解:
@ControllerAdvice
全局,处理所有控制器中的异常@ExceptionHandler
局部,只针对某个控制器中的异常
先有ExceptionHandler
,再有ControllerAdvice
,ExceptionHandler
不能集中处理异常,ControllerAdvice
为弥补此缺点引入,推荐使用ControllerAdvice
。本文介绍ControllerAdvice
的用法,对ExceptionHandler
不作介绍,如需了解可参考相关资料。
错误处理页面:ErrorController
ErrorController
的作用是为servlet设置错误页,默认错误页是Whitelabel,访问不存在的页面就会显示此错误页。
![8200c0aacb690e1a832a77ec7841c116.png](https://i-blog.csdnimg.cn/blog_migrate/098c9f1a58c209223ef927461afd4574.jpeg)
通过继承ErrorController
接口可以设置自定义的错误页。
@RestController
public class MyErrorController implements ErrorController {
@RequestMapping(value = "/error")
public ResponseEntity<Result> error() {
Result res = new Result(404, "页面未找到");
return new ResponseEntity<Result>(res, HttpStatus.NOT_FOUND);