淺談JAVA在項目中如何自定義異常
更新時間:2021年06月29日 11:59:26 作者:L1569850979
今天給大家?guī)淼氖顷P于Java的相關知識,文章圍繞著JAVA在項目中如何自定義異常展開,文中有非常詳細的介紹及代碼示例,需要的朋友可以參考下
JAVA項目中自定義異常
1.數(shù)據(jù)返回處理類
@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 = "返回數(shù)據(jù)", 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 {
//指定出現(xiàn)什么異常執(zhí)行這個方法
@ExceptionHandler(GuliException.class)
@ResponseBody //返回數(shù)據(jù)
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);
}
執(zhí)行結果

使用自定義異常
@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);
}
執(zhí)行結果

到此這篇關于淺談JAVA在項目中如何自定義異常的文章就介紹到這了,更多相關JAVA自定義異常內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Redisson分布式信號量RSemaphore的使用超詳細講解
這篇文章主要介紹了Redisson分布式信號量RSemaphore的使用,基于Redis的Redisson的分布式信號量RSemaphore采用了與java.util.concurrent.Semaphore相似的接口和用法2023-02-02
SpringBoot日志進階實戰(zhàn)之Logback配置經(jīng)驗和方法
本文給大家介紹在SpringBoot中使用Logback配置日志的經(jīng)驗和方法,并提供了詳細的代碼示例和解釋,包括:滾動文件、異步日志記錄、動態(tài)指定屬性、日志級別、配置文件等常用功能,覆蓋日常Logback配置開發(fā)90%的知識點,感興趣的朋友跟隨小編一起看看吧2023-06-06
玩轉spring boot 結合AngularJs和JDBC(4)
玩轉spring boot,這篇文章主要介紹了結合AngularJs和JDBC,玩轉spring boot,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-01-01
Spring Cloud Feign性能優(yōu)化代碼實例
這篇文章主要介紹了Spring Cloud Feign性能優(yōu)化代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-03-03
java讀取文件內容,解析Json格式數(shù)據(jù)方式
這篇文章主要介紹了java讀取文件內容,解析Json格式數(shù)據(jù)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09
SpringBoot中@PostConstruct 注解的實現(xiàn)
在Spring Boot框架中,?@PostConstruct是一個非常有用的注解,它用于在依賴注入完成后執(zhí)行初始化方法,本文將介紹?@PostConstruct的基本概念、使用場景以及提供詳細的代碼示例,感興趣的可以了解一下2024-09-09

