SprinBoot自定义异常(统一异常处理)
统一返回类Result
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result {
private String code;
private String msg;
private Object data;
public static Result success(){
return new Result(Constants.CODE_200,"",null);
}
public static Result success(Object data){
return new Result(Constants.CODE_200,"",data);
}
public static Result error(String code,String msg){
return new Result(code,msg,null);
}
public static Result error(){
return new Result(Constants.CODE_500,"系统错误",null);
}
}
public interface Constants {
String CODE_200="200"; //成功
String CODE_500="500"; //系统错误
String CODE_401="401"; //权限不足
String CODE_400="400"; //参数错误
String CODE_600="600"; //其他业务异常
}
自定义异常类
import com.tian.springboot.controller.common.Result;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class GlobalExceptionHandle {
@ExceptionHandler(ServiceException.class)
@ResponseBody
public Result hanle(ServiceException se){
return Result.error(se.getCode(),se.getMessage());
}
}
import lombok.Getter;
@Getter
public class ServiceException extends RuntimeException{
private String code;
public ServiceException(String code,String msg){
super(msg);
this.code=code;
}
}
使用
private User getUserInfo(UserDTO userDTO){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("username",userDTO.getUsername());
wrapper.eq("password",userDTO.getPassword());
User one;
try {
one = getOne(wrapper);
}catch (Exception e){
LOG.error(e);
throw new ServiceException(Constants.CODE_500,"系统错误");
// throw new ServiceException(Constants.CODE_600,"用户名或密码错误");
}
return one;
}
然后控制台如果报错就会显示你自定义的信息