improve error checking, avoid using panic inside the constructor

This commit is contained in:
c9s 2021-12-08 23:30:58 +08:00
parent 2223ef088c
commit a0f46bf9b8
2 changed files with 13 additions and 9 deletions

View File

@ -70,29 +70,29 @@ type Exchange struct {
doneC chan struct{}
}
func NewExchange(sourceName types.ExchangeName, srv *service.BacktestService, config *bbgo.Backtest) *Exchange {
func NewExchange(sourceName types.ExchangeName, srv *service.BacktestService, config *bbgo.Backtest) (*Exchange, error) {
ex, err := newPublicExchange(sourceName)
if err != nil {
panic(err)
return nil, err
}
if config == nil {
panic(errors.New("backtest config can not be nil"))
return nil, errors.New("backtest config can not be nil")
}
markets, err := bbgo.LoadExchangeMarketsWithCache(context.Background(), ex)
if err != nil {
panic(err)
return nil, err
}
startTime, err := config.ParseStartTime()
if err != nil {
panic(err)
return nil, err
}
endTime, err := config.ParseEndTime()
if err != nil {
panic(err)
return nil, err
}
account := &types.Account{
@ -119,7 +119,7 @@ func NewExchange(sourceName types.ExchangeName, srv *service.BacktestService, co
}
e.resetMatchingBooks()
return e
return e, nil
}
func (e *Exchange) addTrade(trade types.Trade) {
@ -321,5 +321,5 @@ func newPublicExchange(sourceExchange types.ExchangeName) (types.Exchange, error
return okex.New("", "", ""), nil
}
return nil, fmt.Errorf("exchange %s is not supported", sourceExchange)
return nil, fmt.Errorf("public data from exchange %s is not supported", sourceExchange)
}

View File

@ -261,7 +261,11 @@ var BacktestCmd = &cobra.Command{
}
}
backtestExchange := backtest.NewExchange(exchangeName, backtestService, userConfig.Backtest)
backtestExchange, err := backtest.NewExchange(exchangeName, backtestService, userConfig.Backtest)
if err != nil {
return errors.Wrap(err, "failed to create backtest exchange")
}
environ.SetStartTime(startTime)
environ.AddExchange(exchangeName.String(), backtestExchange)