加入收藏 | 设为首页 | 会员中心 | 我要投稿 核心网 (https://www.hxwgxz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 建站 > 正文

SpringBoot 处理异常的几种常见姿势

发布时间:2019-08-29 23:17:13 所属栏目:建站 来源:java互联网架构
导读:一、使用 @ControllerAdvice 和 @ExceptionHandler 处理全局异常 这是目前很常用的一种方式,非常推荐。测试代码中用到了 Junit 5,如果你新建项目验证下面的代码的话,记得添加上相关依赖。 1. 新建异常信息实体类 非必要的类,主要用于包装异常信息。 sr

这种通过 ResponseStatus注解简单处理异常的方法是的好处是比较简单,但是一般我们不会这样做,通过ResponseStatusException会更加方便,可以避免我们额外的异常类。

  1. @GetMapping("/resourceNotFoundException2") 
  2. public void throwException3() { 
  3. throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Sorry, the resourse not found!", new ResourceNotFoundException()); 

使用 Get 请求 localhost:8080/api/resourceNotFoundException2[3] ,服务端返回的 JSON 数据如下,和使用 ResponseStatus 实现的效果一样:

  1.  "timestamp": "2019-08-21T07:28:12.017+0000", 
  2.  "status": 404, 
  3.  "error": "Not Found", 
  4.  "message": "Sorry, the resourse not found!", 
  5.  "path": "/api/resourceNotFoundException3" 

ResponseStatusException 提供了三个构造方法:

  1. public ResponseStatusException(HttpStatus status) { 
  2.  this(status, null, null); 
  3.  } 
  4.  public ResponseStatusException(HttpStatus status, @Nullable String reason) { 
  5.  this(status, reason, null); 
  6.  } 
  7.  public ResponseStatusException(HttpStatus status, @Nullable String reason, @Nullable Throwable cause) { 
  8.  super(null, cause); 
  9.  Assert.notNull(status, "HttpStatus is required"); 
  10.  this.status = status; 
  11.  this.reason = reason; 
  12.  } 

构造函数中的参数解释如下:

•status :http status

•reason :response 的消息内容

•cause :抛出的异常

(编辑:核心网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读