@ControllerAdvice和@ExceptionHandler
1. 使用 @ControllerAdvice和@ExceptionHandler处理全局异常
1. 新建异常信息实体类
非必要的类,主要用于包装异常信息。
package com.test.exception.myexception; public class ErrorResponse {
private String message;
private String errorTypeName; public ErrorResponse(Exception e) {
this(e.getClass().getName(), e.getMessage());
} public ErrorResponse(String errorTypeName, String message) {
this.errorTypeName = errorTypeName;
this.message = message;
} public String getMessage() {
return message;
} public void setMessage(String message) {
this.message = message;
} public String getErrorTypeName() {
return errorTypeName;
} public void setErrorTypeName(String errorTypeName) {
this.errorTypeName = errorTypeName;
}
}
2. 自定义异常类型
package com.test.exception.myexception; public class ReourceNotFoundException extends RuntimeException {
private String message; public ReourceNotFoundException() {
super();
} public ReourceNotFoundException(String message) {
super(message);
this.message = message;
} @Override
public String getMessage() {
return message;
} public void setMessage(String message) {
this.message = message;
}
}
3. 新建异常处理类
我们只需要在类上加上@ControllerAdvice
注解这个类就成为了全局异常处理类,当然你也可以通过 assignableTypes
指定特定的 Controller
类,让异常处理类只处理特定类抛出的异常。
package com.test.exception.handler; import com.test.exception.myexception.ErrorResponse;
import com.test.exception.myexception.ReourceNotFoundException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.server.ResponseStatusException; @ControllerAdvice(assignableTypes = {com.test.exception.controller.ExceptionController.class})
@ResponseBody
public class GlobalExceptionHandler {
ErrorResponse illegalArgumentResponse = new ErrorResponse(new IllegalArgumentException("参数错误!"));
ErrorResponse resourseNotFoundResponse = new ErrorResponse(new com.test.exception.myexception.ReourceNotFoundException("Sorry, the resourse not found!")); @ExceptionHandler(value = Exception.class)// 拦截所有异常, 这里只是为了演示,一般情况下一个方法特定处理一种异常
public ResponseEntity<ErrorResponse> exceptionHandler(Exception e) { if (e instanceof IllegalArgumentException) {
return ResponseEntity.status(400).body(illegalArgumentResponse);
} else if (e instanceof ReourceNotFoundException) {
return ResponseEntity.status(404).body(resourseNotFoundResponse);
}else if(e instanceof ResponseStatusException){
return ResponseEntity.status(502).body(resourseNotFoundResponse);
}
return null;
}
}
4. controller模拟抛出异常
package com.test.exception.controller; import com.test.exception.myexception.ReourceNotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException; @RestController
public class ExceptionController { @GetMapping("/illegalArgumentException")
public void throwException() {
throw new IllegalArgumentException();
} @GetMapping("/resourceNotFoundException")
public void throwException2() {
throw new ReourceNotFoundException(); } @GetMapping("/resourceNotFoundException2")
public void throwException3() {
throw new ResponseStatusException(HttpStatus.BAD_GATEWAY,"The resource not found",new ReourceNotFoundException());
}
}
使用 Get 请求: http://localhost:8080/resourceNotFoundException
{"message":"Sorry, the resourse not found!","errorTypeName":"com.test.exception.myexception.ReourceNotFoundException"}
3. ResponseStatusException
研究 ResponseStatusException 我们先来看看,通过 ResponseStatus
注解简单处理异常的方法(将异常映射为状态码)。
package com.test.exception.myexception; import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(code = HttpStatus.BAD_GATEWAY)
public class ReourceNotFoundException2 extends RuntimeException {
public ReourceNotFoundException2() {
} public ReourceNotFoundException2(String message) {
super(message);
}
}
这种通过 ResponseStatus
注解简单处理异常的方法是的好处是比较简单,但是一般我们不会这样做,通过ResponseStatusException
会更加方便,可以避免我们额外的异常类。
@GetMapping("/resourceNotFoundException2")
public void throwException3() {
throw new ResponseStatusException(HttpStatus.BAD_GATEWAY,"The resource not found",new ReourceNotFoundException());
}
ResponseStatusException
提供了三个构造方法:
public ResponseStatusException(HttpStatus status) {
this(status, null, null);
} public ResponseStatusException(HttpStatus status, @Nullable String reason) {
this(status, reason, null);
} public ResponseStatusException(HttpStatus status, @Nullable String reason, @Nullable Throwable cause) {
super(null, cause);
Assert.notNull(status, "HttpStatus is required");
this.status = status;
this.reason = reason;
}
构造函数中的参数解释如下:
- status : http status
- reason :response 的消息内容
- cause : 抛出的异常
@ControllerAdvice和@ExceptionHandler的更多相关文章
- @ControllerAdvice 和 @ExceptionHandler
@ExceptionHandler的作用是把对不同异常处理抽取到不同的方法中. @ControllerAdvice的作用是把控制器中 @ExceptionHandler.@InitBinder.@Mo ...
- springmvc 全局的异常拦截处理 @ControllerAdvice注解 @ExceptionHandler
第一步: Dispatcher前端控制器的源码中 默认的 private boolean throwExceptionIfNoHandlerFound = false;说明如果没有找到匹配的执行器,不 ...
- @ControllerAdvice + @ExceptionHandler 全局处理 Controller 层异常
@ControllerAdvice 和 @ExceptionHandler 的区别 ExceptionHandler, 方法注解, 作用于 Controller 级别. ExceptionHandle ...
- Spring中通过java的@Valid注解和@ControllerAdvice实现全局异常处理。
通过java原生的@Valid注解和spring的@ControllerAdvice和@ExceptionHandler实现全局异常处理的方法: controller中加入@Valid注解: @Req ...
- 统一异常处理@ControllerAdvice
一.异常处理 有异常就必须处理,通常会在方法后面throws异常,或者是在方法内部进行try catch处理. 直接throws Exception 直接throws Exception,抛的异常太过 ...
- 从源码看全局异常处理器@ExceptionHandler&@ExceptionHandler的生效原理
1.开头在前 日常开发中,几乎我们的项目都会用到异常处理器,我们通常会定制属于自己的异常处理器,来处理项目中大大小小.各种各样的异常.配置异常处理器目前最常用的方式应该是使用@ControllerAd ...
- SpringBoot RESTful 应用中的异常处理小结
转载:https://segmentfault.com/a/1190000006749441 @ControllerAdvice 和 @ExceptionHandler 的区别 ExceptionHa ...
- 详细解说Java Spring的JavaConfig注解 【抄】
抄自: http://www.techweb.com.cn/network/system/2016-01-05/2252188.shtml @RestController spring4为了更方便的支 ...
- Java Spring的 JavaConfig 注解
序 传统spring一般都是基于xml配置的,不过后来新增了许多JavaConfig的注解.特别是springboot,基本都是清一色的java config,不了解一下,还真是不适应.这里备注一下. ...
随机推荐
- C#中一些常用的方法使用
一.string.Empty string.Empty就相当于 "" ,一般用于字符串的初始化 , 比如: string a; Console.WriteLine(a);//这里会 ...
- python第三方库的更新和安装指定版本
安装指定版本: pip install openpyxl==2.3.4 更新到最新版本: pip install --upgrade openpyxl
- 【题解】[USACO2007 OCT]Obstacle Course-C++
题目Description考虑一个 N x N (1 <= N <= 100)的有1个个方格组成的正方形牧场.有些方格是奶牛们不能踏上的,它们被标记为了’x’.例如下图: . . B x ...
- windows平台下MySQl的安装、破解和使用
#1.下载:MySQL Community Server 5.7.16 http://dev.mysql.com/downloads/mysql/ #2.解压 如果想要让MySQL安装在指定目录,那么 ...
- 提交项目到Github
create a new repository on the command line git init git add README.md git commit -m "first com ...
- Python数据类型之数值-Python基础前传(5)
学习任何一门学科或者手艺,最忌讳的就是想的太多,做的太少: 有很多朋友私信问我:jacky,我们该如何选择Python的课程?或是我们该如何选择Mysql课程?到底谁的课件和书籍才是最好的? 借着今天 ...
- 三十、CentOS 7之systemd
一.系统启动流程 POST --> bootloader --> MBR工作 --> kernel(initramfs/initrd) --> ro rootfs --> ...
- 三个div并排
css: .div-inline{ display:inline} html: <div class="div-inline">第一个div盒子</div> ...
- codeforces gym #101161E - ACM Tax(lca+主席树)
题目链接: http://codeforces.com/gym/101161/attachments 题意: 给出节点数为$n$的树 有$q$次询问,输出$a$节点到$b$节点路程中,经过的边的中位数 ...
- input上传mp3格式文件,预览并且获取时间
<input type="file" id="file" name="file" class="upfile" o ...