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);}
执行结果
全局异常定义
如果有异常Exception会被这里的全局异常捕捉,并抛出
持续更新!