1. 统一异常处理配置
package com.yangxz.response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.DuplicateKeyException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 统一异常处理 */ @ControllerAdvice public class GlobalExceptionHandlerAdvice { Logger logger = LoggerFactory.getLogger(GlobalExceptionHandlerAdvice.class); @ExceptionHandler(value = Exception.class) @ResponseBody public R exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception exception) { logger.info("异常类型:" + exception.getClass().getSimpleName()); String msg = "出错了。。。"; String data = null; /*根据异常类型,设置不同的数据*/ if (exception instanceof DuplicateKeyException) { data = "字段冲突"; // response.setStatus(404); } return R.error().message(msg).data(data); } }
2. userController添加用户新增接口
package com.yangxz.controller; import com.yangxz.dto.UserDTO; import com.yangxz.entity.User; import com.yangxz.service.UserService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.util.List; /** * <p> * 前端控制器 * </p> * * @author yangxz * @since 2022-06-30 */ @Api(tags = "用户管理") @RestController @RequestMapping("/user") public class UserController { @Resource private UserService userService; @ApiOperation("用户列表") @GetMapping("/list") public List<User> list() { return userService.list(); } @ApiOperation("用户新增") @PostMapping("/add") public String add(@RequestBody UserDTO.AddDTO dto) { User user = new User(); user.setUsername(dto.getUsername()); user.setPassword(dto.getPassword()); return userService.save(user) ? "新增成功" : "新增失败"; } }
3. 新增用户新增请求体
package com.yangxz.dto; import lombok.Data; @Data public class UserDTO { @Data public static class AddDTO{ private String username; private String password; } }
4. 测试用户新增接口
user表中对username设置了唯一索引,插入相同的数据就会报错,数据库中已经有一条admin的记录