Exception handling
Error handling
The Go language marks errors by the error type, and the following two error types are defined:
| Error type | Description |
|---|---|
| BceClientError | Errors caused by user operations |
| BceServiceError | Errors returned by the ET service |
When users invoke service APIs through the SDK, the required results will be returned along with any errors that occur. Users can access detailed error information and handle these errors. An example is provided below:
1createEtResult, err := etClient.CreateEtDcphy(args)
2if err != nil {
3 switch realErr := err.(type) {
4 case *bce.BceClientError:
5 fmt.Println("client occurs error:", realErr.Error())
6 case *bce.BceServiceError:
7 fmt.Println("service occurs error:", realErr.Error())
8 default:
9 fmt.Println("unknown error:", err)
10 }
11}
12fmt.Println("create et success, etId:", createEtResult.Id)
Client exception
A client exception occurs when the client faces issues during request transmission or file uploads to Baidu AI Cloud services. For instance, a BceClientError will be returned in cases of network failures or I/O errors.
Server exception
A server exception occurs when there are errors on the Baidu AI Cloud server side. The service will return detailed error messages to help with troubleshooting. For details on specific server-side exceptions, consult the official documentation of the respective service.
SDK logging
The GO SDK has independently implemented a logging module that supports six levels, three output destinations (standard output, standard error, file), and basic format settings. Its import path is github.com/baidubce/bce-sdk-go/util/log. When outputting to a file, it supports setting five log rolling modes (no rolling, rolling by day, rolling by hour, rolling by minute, rolling by size). In this case, the directory for output log files also needs to be set.
This logging module does not rely on any external dependencies. Developers working with the GO SDK can directly integrate this logging module into their projects. They can either use the package-level log object provided by the GO SDK or create a new log object. Refer to the examples below for details:
1// Directly use the package-level global log object (will be output together with the GO SDK’s own logs)
2log.SetLogHandler(log.STDERR)
3log.Debugf("%s", "logging message using the log package in the sdk")
4 // Create a new log object (output logs according to custom settings, separated from the GO SDK’s log output)
5myLogger := log.NewLogger()
6myLogger.SetLogHandler(log.FILE)
7myLogger.SetLogDir("/home/log")
8myLogger.SetRotateType(log.ROTATE_SIZE)
9myLogger.Info("this is my own logger from the sdk")
