编程心得:异常的使用
在进行WEB后端开发时,我们通常将代码进行分层处理,controller,service,dao
controller层:负责处理用户请求和响应,通常将接受的请求参数进行校验,以及向客户端输出符合要求的数据
service层:解决具体的业务逻辑
dao层:与数据库进行交互,封装对数据的操作
在进行代码开发时,发送了影响正常业务流程的错误,并且不能明确符合方法要求的处理结果时,才抛出异常
例如在controller进行请求参数校验时,已明确知道xx参数不符合要求,如xx参数不能为空,xx参数数值不符合要求,或超过规定值得范围等有明确的处理结果时,就应直接返回处理结果
代码示例
@Data
public class UserPO {
private Integer id;
private String name;
private Integer age;
private Integer sex;
private String addr;
private String phone;
}
@Data
public class UserVO {
private Integer id;
private String name;
private Integer age;
}
@RestController
@RequestMapping("/user")
public class Controller {
@Resource
private ServiceImpl service;
@GetMapping("/{id}")
public ResponseVO getUser(@PathVariable Integer id) {
if (id == null) {
return ResponseFactory.err("id不能为空");
}
if (id < 0) {
return ResponseFactory.err("id数值非法");
}
UserPO user = service.getUser(id);
if (user != null) {
UserVO vo = new UserVO();
BeanUtils.copyProperties(user, vo);
return ResponseFactory.ok(vo);
}
return ResponseFactory.ok();
}
@PutMapping
public ResponseVO updateUser(@RequestBody UserPO po) {
Integer id = po.getId();
if (id == null) {
return ResponseFactory.err("id不能为空");
}
if (id < 0) {
return ResponseFactory.err("id数值非法");
}
boolean success = service.updateUser(po);
if (!success) {
return ResponseFactory.err("修改用户信息失败");
}
return ResponseFactory.ok();
}
}
@Service
public class ServiceImpl {
@Resource
private UserDao userDao;
public UserPO getUser(Integer userId) {
if (userId == null || userId < 0) {
return null;
}
return userDao.getUser(userId);
}
/**
* 更新用户信息
* return true: 修改成功; false:修改失败
*/
public boolean updateUser(UserPO po) {
UserPO user = getUser(po.getId());
// 用户不存在,影响正常的业务流程,且没有明确符合方法要求的处理结果,抛出异常
if (user == null) {
throw BizException.newInstance("用户不存在");
}
BeanUtils.copyProperties(po, user);
Integer result = userDao.updateUser(user);
return result != null && result > 0;
}
}
public interface UserDao {
UserPO getUser(Integer userId);
Integer updateUser(UserPO po);
}