@RestController
@RequestMapping("/user")
public class UserController {
@Resource
User user;
@GetMapping("/query")
public User query(Integer id) {
if (id == null) {
throw new JavasmException(ExceptionEnum.Parameter_NUll);
}
return user;
}
}
二、方式二
1 配置全局异常捕获类
@RestControllerAdvice
public class ProjectExceptionAdvice {
@ExceptionHandler(SystemException.class) //拦截异常
public HashMap<String, Object> doException(SystemException e){
// 记录日志
// 发送消息给运维
// 发送邮件给开发人员
HashMap<String, Object> map = new HashMap<>();
map.put("code",e.getCode());
map.put("msg",e.getMessage());
map.put("data",null);
return map;
}
@ExceptionHandler(BusinessException.class) //拦截异常
public HashMap<String, Object> doException(BusinessException e){
HashMap<String, Object> map = new HashMap<>();
map.put("code",e.getCode());
map.put("msg",e.getMessage());
map.put("data",null);
return map;
}
}
2 配置自定义异常类
public class BusinessException extends RuntimeException{
private Integer code;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public BusinessException(String message, Integer code) {
super(message);
this.code = code;
}
public BusinessException(String message, Throwable cause, Integer code) {
super(message, cause);
this.code = code;
}
}