ошибки
This commit is contained in:
parent
cefc07c2c2
commit
0399e1400c
@ -18,7 +18,7 @@ Switch
|
|||||||
Структуры (Structs)
|
Структуры (Structs)
|
||||||
Методы (Methods)
|
Методы (Methods)
|
||||||
Интерфейсы (Interfaces)
|
Интерфейсы (Interfaces)
|
||||||
Errors
|
Ошибки (Errors)
|
||||||
Goroutines
|
Goroutines
|
||||||
Channels
|
Channels
|
||||||
Channel Buffering
|
Channel Buffering
|
||||||
|
@ -1,11 +1,11 @@
|
|||||||
// In Go it's idiomatic to communicate errors via an
|
// В Go принято сообщать об ошибках через явное, отдельное
|
||||||
// explicit, separate return value. This contrasts with
|
// возвращаемое значение. Это контрастирует с исключениями,
|
||||||
// the exceptions used in languages like Java and Ruby and
|
// используемыми в таких языках, как Java и Ruby, и
|
||||||
// the overloaded single result / error value sometimes
|
// перегруженным одиночным значением результата/ошибки,
|
||||||
// used in C. Go's approach makes it easy to see which
|
// иногда используемым в подходе C. Go, позволяет легко
|
||||||
// functions return errors and to handle them using the
|
// увидеть, какие функции возвращают ошибки, и обрабатывать
|
||||||
// same language constructs employed for any other,
|
// их, используя те же языковые конструкции, которые
|
||||||
// non-error tasks.
|
// используются для любых других задач без ошибок.
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
@ -14,26 +14,26 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
)
|
)
|
||||||
|
|
||||||
// By convention, errors are the last return value and
|
// По соглашению, ошибки - это последнее возвращаемое
|
||||||
// have type `error`, a built-in interface.
|
// значение с типом `error` в стандартной реализации.
|
||||||
func f1(arg int) (int, error) {
|
func f1(arg int) (int, error) {
|
||||||
if arg == 42 {
|
if arg == 42 {
|
||||||
|
|
||||||
// `errors.New` constructs a basic `error` value
|
// `errors.New` создает стандартную `ошибку` с
|
||||||
// with the given error message.
|
// указаннным сообщением
|
||||||
return -1, errors.New("can't work with 42")
|
return -1, errors.New("can't work with 42")
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// A `nil` value in the error position indicates that
|
// Значение `nil` в поле ошибки, говорит о том, что
|
||||||
// there was no error.
|
// ошибок нет.
|
||||||
return arg + 3, nil
|
return arg + 3, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// It's possible to use custom types as `error`s by
|
// Можно использовать пользовательские типы в качестве
|
||||||
// implementing the `Error()` method on them. Here's a
|
// ошибок, применяя к ним метод `Error()`. Вот вариант
|
||||||
// variant on the example above that uses a custom type
|
// в примере выше, который использует пользовательский
|
||||||
// to explicitly represent an argument error.
|
// тип для явного представления ошибки аргумента.
|
||||||
type argError struct {
|
type argError struct {
|
||||||
arg int
|
arg int
|
||||||
prob string
|
prob string
|
||||||
@ -46,9 +46,9 @@ func (e *argError) Error() string {
|
|||||||
func f2(arg int) (int, error) {
|
func f2(arg int) (int, error) {
|
||||||
if arg == 42 {
|
if arg == 42 {
|
||||||
|
|
||||||
// In this case we use `&argError` syntax to build
|
// В этом случае мы используем синтаксис `&argError`
|
||||||
// a new struct, supplying values for the two
|
// для создания новой структуры, предоставляя
|
||||||
// fields `arg` and `prob`.
|
// значения для двух полей `arg` и `prob`.
|
||||||
return -1, &argError{arg, "can't work with it"}
|
return -1, &argError{arg, "can't work with it"}
|
||||||
}
|
}
|
||||||
return arg + 3, nil
|
return arg + 3, nil
|
||||||
@ -56,10 +56,10 @@ func f2(arg int) (int, error) {
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
|
||||||
// The two loops below test out each of our
|
// Два цикла ниже тестируют каждую из наших функций,
|
||||||
// error-returning functions. Note that the use of an
|
// возвращающих ошибки. Обратите внимание, что
|
||||||
// inline error check on the `if` line is a common
|
// использование встроенной проверки ошибок в строке
|
||||||
// idiom in Go code.
|
// `if` является обычный явлением в Go.
|
||||||
for _, i := range []int{7, 42} {
|
for _, i := range []int{7, 42} {
|
||||||
if r, e := f1(i); e != nil {
|
if r, e := f1(i); e != nil {
|
||||||
fmt.Println("f1 failed:", e)
|
fmt.Println("f1 failed:", e)
|
||||||
@ -75,10 +75,9 @@ func main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// If you want to programmatically use the data in
|
// Если вы хотите использовать данные в пользовательской
|
||||||
// a custom error, you'll need to get the error as an
|
// ошибке, вам нужно получить ошибку как экземпляр
|
||||||
// instance of the custom error type via type
|
// пользовательского типа через утверждение типа.
|
||||||
// assertion.
|
|
||||||
_, e := f2(42)
|
_, e := f2(42)
|
||||||
if ae, ok := e.(*argError); ok {
|
if ae, ok := e.(*argError); ok {
|
||||||
fmt.Println(ae.arg)
|
fmt.Println(ae.arg)
|
||||||
|
@ -6,5 +6,5 @@ f2 failed: 42 - can't work with it
|
|||||||
42
|
42
|
||||||
can't work with it
|
can't work with it
|
||||||
|
|
||||||
# See this [great post](http://blog.golang.org/2011/07/error-handling-and-go.html)
|
# Посмотрите [эту статью](http://blog.golang.org/2011/07/error-handling-and-go.html)
|
||||||
# on the Go blog for more on error handling.
|
# в блоге Go для более подробной информации об ошибках.
|
||||||
|
Loading…
x
Reference in New Issue
Block a user