淺談JAVA在項目中如何自定義異常
更新時間:2021年06月29日 11:59:26 作者:L1569850979
今天給大家?guī)淼氖顷P(guān)于Java的相關(guān)知識,文章圍繞著JAVA在項目中如何自定義異常展開,文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下
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í)行結(jié)果

使用自定義異常
@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í)行結(jié)果

到此這篇關(guān)于淺談JAVA在項目中如何自定義異常的文章就介紹到這了,更多相關(guān)JAVA自定義異常內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot+WebSocket實現(xiàn)多人在線聊天案例實例
本文主要介紹了SpringBoot+WebSocket實現(xiàn)多人在線聊天案例,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02
WebSocket實現(xiàn)聊天室業(yè)務(wù)
這篇文章主要為大家詳細(xì)介紹了WebSocket實現(xiàn)聊天室業(yè)務(wù),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-08-08
Springboot多環(huán)境開發(fā)及使用方法
這篇文章主要介紹了Springboot多環(huán)境開發(fā)及多環(huán)境設(shè)置使用、多環(huán)境分組管理的相關(guān)知識,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-03-03
Spring Security自定義認(rèn)證器的實現(xiàn)代碼
這篇文章主要介紹了Spring Security自定義認(rèn)證器的實現(xiàn)代碼,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-06-06

