springboot 前后端分离项目,在后端代码发生异常时,能够统一接口的形式返回
最终效果
定义一个异常统一类 (出错时 负责返回的信息):
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class ServiceException extends RuntimeException {
private Integer code;
public ServiceException(){
super("系统错误");
this.code=500;
}
public ServiceException(int code,String msg){
super(msg);
this.code=code;
}
}
全局异常类注册(不定义 不能返回给前端 只在控制台输出)
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ServiceException.class)
@ResponseBody
public ComRes handle(ServiceException se){
return ComRes.error(se.getMessage());
}
}
使用抛出自定义异常
返回一个统一接口类效果也相同 ,可能不规范



