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

SpringBoot 处理赏罚非常的几种常见姿势

发布时间:2019-08-29 21:35:33 所属栏目:建站 来源: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 :抛出的非常

(编辑:湖南网)

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

热点阅读