浅谈JAVA在项目中如何自定义异常

JAVA项目中自定义异常

1.数据返回处理类

@Datapublic 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@NoArgsConstructorpublic class GuliException extends  RuntimeException{    private Integer code;    private String msg;}

3.定义异常处理

@ControllerAdvicepublic 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自定义异常内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

莫找借口失败,只找理由成功。

浅谈JAVA在项目中如何自定义异常

相关文章:

你感兴趣的文章:

标签云: