淺談JAVA在項目中如何自定義異常
更新時間:2021年06月29日 11:59:26 作者:L1569850979
今天給大家?guī)淼氖顷P于Java的相關知識,文章圍繞著JAVA在項目中如何自定義異常展開,文中有非常詳細的介紹及代碼示例,需要的朋友可以參考下
JAVA項目中自定義異常
1.數(shù)據返回處理類
@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ù)據", 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ù)據 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ù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot+WebSocket實現(xiàn)多人在線聊天案例實例
本文主要介紹了SpringBoot+WebSocket實現(xiàn)多人在線聊天案例,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02Springboot多環(huán)境開發(fā)及使用方法
這篇文章主要介紹了Springboot多環(huán)境開發(fā)及多環(huán)境設置使用、多環(huán)境分組管理的相關知識,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-03-03Spring Security自定義認證器的實現(xiàn)代碼
這篇文章主要介紹了Spring Security自定義認證器的實現(xiàn)代碼,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-06-06