这篇文章主要讲解了“JAVA在项目中怎么自定义异常”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“JAVA在项目中怎么自定义异常”吧!JAVA项目中自定义异常1.数据返回处理类@Datapub
这篇文章主要讲解了“JAVA在项目中怎么自定义异常”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“JAVA在项目中怎么自定义异常”吧!
1.数据返回处理类
@Datapublic class R<T> implements Serializable { private static final long serialVersionUID = -8497670085742879369L; @apiModelProperty(value = "返回码", example = "200") private Integer code=200; @ApiModelProperty(value = "返回消息", example = "") private String message="SUCCESS"; @ApiModelProperty(value = "返回数据", example = "") private T data; private R() { } public R(T data) { this.data = data; } public R(Integer code,String message) { this.code=code; this.message = message; }}
2.新建自定义异常
@Data@AllArgsConstructor@NoArgsConstructorpublic class GuliException extends RuntimeException{ private Integer code; private String msg;}
3.定义异常处理
@ControllerAdvicepublic class GlobalExceptionHandler { //指定出现什么异常执行这个方法 @ExceptionHandler(GuliException.class) @ResponseBody //返回数据 public R error(GuliException e){ e.printStackTrace(); return new R(e.getCode(),e.getMsg()); }}
不使用异常处理示例
@GetMapping("/testError") @ApiOperation(value = "测试异常处理") public R<UserVO> testError(@RequestParam("id") String id){ UserVO userVO=new UserVO(); SysUser byId = sysUserService.getById(id); BeanUtils.copyProperties(byId,userVO); return new R<>(userVO); }
执行结果
使用自定义异常
@GetMapping("/testCheck") @ApiOperation(value = "测试返回值正常处理") public R<Boolean> testCheck(){ try { int i=10/0; }catch (Exception e){ e.printStackTrace(); throw new GuliException(1001,"错误测试"); } return new R<>(true); }
执行结果
感谢各位的阅读,以上就是“JAVA在项目中怎么自定义异常”的内容了,经过本文的学习后,相信大家对JAVA在项目中怎么自定义异常这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程网,小编将为大家推送更多相关知识点的文章,欢迎关注!
--结束END--
本文标题: JAVA在项目中怎么自定义异常
本文链接: https://www.lsjlt.com/news/296566.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-05
2024-05-05
2024-05-05
2024-05-05
2024-05-05
2024-05-05
2024-05-05
2024-05-05
2024-05-05
2024-05-05
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0