Go error handling idea

image

Recently (and not only recently), many copies have been broken about the inconvenience of error handling in Go.

The essence of the claims is that direct use:

customVar, err := call()
if err != nil {
	doSomething(err)
	return err
}

on large numbers of repetitions is much less convenient than the classic:

try {
	String customVar = call();
} catch (BadException e) {
	doSomething(e);
	sendException();
}

One can argue for a long time both on the subject matter of the claims and on roundabout maneuvers , however, the logic in the “package” approach does exist.

In this connection, I had an idea about handling exceptions without much departure from the “Go-way”. The option is not working - just my imagination.

It would look like this:

try err {
	customVar1, err := call1()
	customVar2, err := call2()
	customVar3, err := call3()
} catch {
	doSomething(err)
	return err
}

The general idea is this: immediately after try, a variable (in our case err) of the error type is declared, the scope of which is the entire try ... catch block. Further, each time a variable is assigned a new value inside the try block, the compiler checks it for nil, and if an error is returned, a transition to the catch block follows. Theoretically, this is not a very expensive operation; performance should not be affected.

It is also possible to assign several variables, such as:

try errIo, errNet {
	customVarIo1, errIo := callIo1()
	customVarIo2, errIo := callIo2()
	customVarNet1, errNet := callNet1()
	customVarNet2, errNet := callNet2()
} catch {
	if errIo != nil {
		doSomething(errIo)
		return errIo
	} else {
		doSomething(errNet)
		return errNet
	}
}

In this case, the example is not very illustrative, however, with a large amount of code inside try, it can be useful to group errors so that in catch they are not reduced to:

switch err {
	case net.Error1:
		doSomethingWithNetError()
	case net.Error2:
		doSomethingWithNetError()
	case io.Error1:
		doSomethingWithIoError()
	case io.Error2:
		doSomethingWithIoError()
}

In general, I have everything. Scold.

Also popular now: