JAVA项目中自定义异常
1.数据返回处理类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | @Data public 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.新建自定义异常
1 2 3 4 5 6 7 8 9 | @Data @AllArgsConstructor @NoArgsConstructor public class GuliException extends RuntimeException{ private Integer code; private String msg; } |
3.定义异常处理
1 2 3 4 5 6 7 8 9 10 11 12 | @ControllerAdvice public class GlobalExceptionHandler { //指定出现什么异常执行这个方法 @ExceptionHandler (GuliException. class ) @ResponseBody //返回数据 public R error(GuliException e){ e.printStackTrace(); return new R(e.getCode(),e.getMsg()); } } |
4.不使用异常处理示例
1 2 3 4 5 6 7 8 9 | @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); } |
执行结果
使用自定义异常
1 2 3 4 5 6 7 8 9 10 11 | @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自定义异常内容请搜索自学编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持自学编程网!
- 本文固定链接: https://zxbcw.cn/post/216241/
- 转载请注明:必须在正文中标注并保留原文链接
- QQ群: PHP高手阵营官方总群(344148542)
- QQ群: Yii2.0开发(304864863)