浅谈JAVA在项目中如何自定义异常
更新时间:2021年06月29日 11:59:26 作者:L1569850979
今天给大家带来的是关于Java的相关知识,文章围绕着JAVA在项目中如何自定义异常展开,文中有非常详细的介绍及代码示例,需要的朋友可以参考下
JAVA项目中自定义异常
1.数据返回处理类
@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.新建自定义异常
@Data
@AllArgsConstructor
@NoArgsConstructor
public class GuliException extends RuntimeException{
private Integer code;
private String msg;
}
3.定义异常处理
@ControllerAdvice
public class GlobalExceptionHandler {
//指定出现什么异常执行这个方法
@ExceptionHandler(GuliException.class)
@ResponseBody //返回数据
public R error(GuliException e){
e.printStackTrace();
return new R(e.getCode(),e.getMsg());
}
}
4.不使用异常处理示例
@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自定义异常内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Redisson分布式信号量RSemaphore的使用超详细讲解
这篇文章主要介绍了Redisson分布式信号量RSemaphore的使用,基于Redis的Redisson的分布式信号量RSemaphore采用了与java.util.concurrent.Semaphore相似的接口和用法2023-02-02
SpringBoot日志进阶实战之Logback配置经验和方法
本文给大家介绍在SpringBoot中使用Logback配置日志的经验和方法,并提供了详细的代码示例和解释,包括:滚动文件、异步日志记录、动态指定属性、日志级别、配置文件等常用功能,覆盖日常Logback配置开发90%的知识点,感兴趣的朋友跟随小编一起看看吧2023-06-06
玩转spring boot 结合AngularJs和JDBC(4)
玩转spring boot,这篇文章主要介绍了结合AngularJs和JDBC,玩转spring boot,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2017-01-01
SpringBoot中@PostConstruct 注解的实现
在Spring Boot框架中, @PostConstruct是一个非常有用的注解,它用于在依赖注入完成后执行初始化方法,本文将介绍 @PostConstruct的基本概念、使用场景以及提供详细的代码示例,感兴趣的可以了解一下2024-09-09


最新评论