Skip to content

Commit 806c377

Browse files
committed
traduccion capitulo 11
1 parent eaa65c5 commit 806c377

File tree

5 files changed

+116
-118
lines changed

5 files changed

+116
-118
lines changed

eBook/11.0.md

+6-6
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1-
# 11 Error Handling, Debugging, and Testing
1+
# 11 Manejo de errores, depurar y probar
22

3-
We often see the majority of a programmer's "programming" time spent on checking for bugs and working on bug fixes. Whether you are prepared to amend the code or re-configurable systems, almost all spend a lot of time troubleshooting and testing, we feel that the outside world is a designer programmer, able to put a system has never done, is a very great work, but the work is quite interesting, but in fact every day we are wandering in troubleshooting, debugging, testing between. Of course, if you have good habits and technology solutions to confront these questions, then you are likely to minimize troubleshooting time, and as much as possible to spend time in the more valuable things.
3+
A menudo vemos la mayor parte del tiempo "programación" de un programador dedicado a la comprobación de errores y trabajando en correcciones de errores. Si usted está dispuesto a modificar el código o los sistemas de re-configurables, casi todo pasa mucho tiempo de resolución de problemas y pruebas, nos parece que el mundo exterior es un programador diseñador, capaz de poner un sistema nunca lo ha hecho, es una obra muy grande , pero el trabajo es muy interesante, pero en realidad todos los días nos están vagando en la solución de problemas, depuración, prueba el medio. Por supuesto, si usted tiene buenos hábitos y soluciones de tecnología para hacer frente a estas preguntas, entonces usted está probablemente para minimizar el tiempo de resolución de problemas, y tanto como sea posible para pasar el tiempo en las cosas más valiosas.
44

5-
But unfortunately a lot of programmers unwilling error handling, debugging and testing capabilities to work on, leading to the back on the line after the application for errors, positioning spend more time. So we do a good job in the design of the application before the error-handling plan, test cases, etc., then the future to modify the code, upgrade the system will become simpler.
5+
Pero, por desgracia muchos programadores capacidades de manejo de errores, depuración y pruebas que no quieren trabajar, que conduce a la parte de atrás en la línea después de la aplicación de los errores, el posicionamiento pasa más tiempo. Así que hacemos un buen trabajo en el diseño de la aplicación antes de que el plan de control de errores, casos de prueba, etc, entonces el futuro para modificar el código, actualice el sistema a ser más simple.
66

7-
Web application development process, errors are inevitable, so how better to find the cause of the error, solve the problem? Section 11.1 describes how to handle errors Go language, how to design your own package, error handling function, 11.2 section describes how to use GDB to debug our program, the dynamic operation of various variable information, operation monitoring and debugging.
7+
Proceso de desarrollo de aplicaciones Web, los errores son inevitables, por lo que la mejor manera de encontrar la causa del error, solucionar el problema? Sección 11.1 describe cómo controlar los errores Ir lenguaje, la forma de diseñar su propio paquete, la función de control de errores, 11,2 sección describe cómo usar GDB para depurar nuestro programa, el funcionamiento dinámico de la diversa información variable de seguimiento del tránsito y la depuración.
88

9-
Section 11.3 of the Go language will explore in depth the unit tests and examples how to write unit tests, Go unit test specification how to define rules to ensure that future upgrades to modify run the appropriate test code can be minimized test.
9+
Sección 11.3 del lenguaje Go explorará en profundidad las pruebas unitarias y ejemplos de cómo escribir pruebas unitarias, vaya especificación prueba unitaria cómo definir reglas para garantizar que las futuras actualizaciones de modificar ejecutar el código de prueba adecuado puede minimizar prueba.
1010

11-
For a long time, develop good debugging, testing has been a lot of programmers accustomed to evade thing, so now you do not escape, from your current project development, from the beginning to learn Go Web developers to develop good habits.
11+
Durante mucho tiempo, desarrollar una buena depuración, las pruebas han sido un montón de programadores acostumbrados a evadir la cosa, por lo que ahora no escapar, de su desarrollo actual del proyecto, desde el principio de aprender Go a los desarrolladores web para desarrollar buenos hábitos.
1212

1313
## Links
1414

eBook/11.1.md

+28-28
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,27 @@
1-
# 11.1 Error handling
1+
# 11.1 La gestión de errores
22

3-
Go language major design criterion is : simple to understand , simple is the syntax similar to C is fairly simple to understand refers to any statement is obvious , does not contain any hidden things in the error-handling program design also implement this idea . We know that there is in the C language by returning -1 or NULL to indicate the kind of error message , but for users who do not view the API documentation , the return value never know exactly what does it mean , for example: return 0 is success or failure , and Go defines a type called the error to explicitly express errors. When in use, by the returned error variable nil comparison to determine whether the operation was successful. For example `os.Open` function opens the file will return a failure of the error variable is not nil
3+
El principal criterio del diseño de go es: fácil de entender, simple es la sintaxis similar a C es bastante sencillo de entender se refiere a cualquier declaración es evidente, no contiene cosas ocultas en el diseño del programa de gestión de errores también poner en práctica esta idea. Sabemos que existe en el lenguaje C, devolviendo -1 o NULL para indicar el tipo de mensaje de error, pero para los usuarios que no ven la documentación de la API, el valor de retorno no sabemos exactamente lo que significa, por ejemplo: return 0 es el éxito o el fracaso, y Go define un tipo llamado el error de expresar explícitamente errores. Cuando está en uso, por la comparación nula variable de error devuelto para determinar si la operación se ha realizado correctamente. Por ejemplo os.Open función abre el archivo volverá un fracaso de la variable not nil
44

55
func Open (name string) (file * File, err error)
66

7-
Here's an example by calling `os.Open` open a file if an error occurs, it will call the `log.Fatal` to output an error message :
7+
He aquí un ejemplo llamando os.Open abrir un archivo si se produce un error, se llamará a la log.Fatal mostrar un mensaje de error::
88

99
f, err := os.Open("filename.ext")
1010
if err != nil {
1111
log.Fatal(err)
1212
}
1313

14-
Similar to the `os.Open` function, the standard package of all possible errors of the API will return an error variable to facilitate error handling, this section will detail error type design, and discuss how to develop Web applications to better handle error.
14+
Similar a la os.Open función, el paquete estándar de todos los posibles errores de la API devolverá una variable de error para facilitar el manejo de errores, esta sección Tipo de error detalle diseño, y discutir cómo desarrollar aplicaciones Web para una mejor error de identificador.
1515

1616
## Error type
1717

18-
`error` is an interface type, with this definition:
18+
`error` es un tipo de interfaz, con esta definición:
1919

2020
type error interface {
2121
Error() string
2222
}
2323

24-
`error` is a built-in interface type, we can / builtin / pack below to find the appropriate definition. And we have a lot of internal error is used inside the package packet errors following implementation structure errorString private
24+
`error` es una continuación / paquete integrado tipo de interfaz, podemos / orden interna para encontrar la definición adecuada. Y lo que tenemos es utilizado una gran cantidad de error interno dentro de los errores de paquetes de paquetes siguiente estructura de ejecución errorString privado
2525

2626
// errorString is a trivial implementation of error.
2727
type errorString struct {
@@ -32,14 +32,14 @@ Similar to the `os.Open` function, the standard package of all possible errors o
3232
return e.s
3333
}
3434

35-
You can `errors.New` put a string into errorString, in order to get a meet the interface error object whose internal implementation is as follows:
35+
usted puede `errors.New` poner una cadena en errorString, con el fin de conseguir una reunión el objeto de error de interfaz cuya implementación interna es el siguiente:
3636

37-
// New returns an error that formats as the given text.
37+
// Nueva devuelve un error que da formato como el texto dado
3838
func New(text string) error {
3939
return &errorString{text}
4040
}
4141

42-
The following example demonstrates how to use `errors.New`:
42+
El siguiente ejemplo muestra cómo utilizar `errors.New`:
4343

4444
func Sqrt(f float64) (float64, error) {
4545
if f < 0 {
@@ -48,16 +48,16 @@ The following example demonstrates how to use `errors.New`:
4848
// implementation
4949
}
5050

51-
In the following example, we call the Sqrt when passing a negative number , and then you get the error object is non-nil , nil compared with this object , the result is true, so `fmt.Println` (fmt package when dealing with error calls the error method ) is called to output error , look at the following sample code to call :
51+
En el siguiente ejemplo, que llamamos el Sqrt al pasar un número negativo, y entonces obtenemos el objeto de error es no-nil, nil en comparación con este objeto, el resultado es verdadero, por lo fmt.Println (paquete fmt cuando se trata de llamadas de error el método de error) se llama a un error de salida, mira el siguiente código de ejemplo para llamar:
5252

5353
f, err := Sqrt(-1)
5454
if err != nil {
5555
fmt.Println(err)
5656
}
5757

58-
## Custom Error
58+
## Error Custom
5959

60-
Through the above description we know that error is an interface, so in the realization of their package, by defining the structure implements this interface , we can realize their error definitions , see the package from Json Example:
60+
A través de la descripción anterior sabemos que el error es una interfaz, por lo que en la realización de su paquete, mediante la definición de la estructura implementa esta interfaz, podemos darnos cuenta de sus definiciones de error, consulte el paquete de Json Ejemplo:
6161

6262
type SyntaxError struct {
6363
msg string // error description
@@ -66,7 +66,7 @@ Through the above description we know that error is an interface, so in the real
6666

6767
func (e * SyntaxError) Error() string {return e.msg}
6868

69-
Error Offset field in the call time will not be printed , but we can get through a type assertion error type , then you can print an appropriate error message , see the following examples:
69+
Error campo Desplazamiento en el tiempo de la llamada no se imprimirá, pero podemos obtener a través de un tipo de error de aserción de tipo, entonces usted puede imprimir un mensaje de error apropiado, consulte los siguientes ejemplos:
7070

7171
if err := dec.Decode(&val); err != nil {
7272
if serr, ok := err.(*json.SyntaxError); ok {
@@ -76,7 +76,7 @@ Error Offset field in the call time will not be printed , but we can get through
7676
return err
7777
}
7878

79-
Note that, the function returns a custom error, the return value is set to recommend error type, rather than a custom error types, particular note should not be pre-declare custom error types of variables. For example:
79+
Tenga en cuenta que, la función devuelve un error personalizado, el valor devuelto se establece en recomendar el tipo de error, en lugar de un tipo de error personalizados, nota en particular no debe ser previamente declarar tipos de error personalizados de variables. Por ejemplo:
8080

8181
func Decode() *SyntaxError {
8282
// error , which may lead to the upper caller err! = nil judgment is always true.
@@ -89,7 +89,7 @@ Note that, the function returns a custom error, the return value is set to recom
8989

9090
Cause see http://golang.org/doc/faq#nil_error
9191

92-
The above example shows how a simple custom Error type. But if we need more sophisticated error handling it? At this point, we have to refer to net package approach:
92+
El ejemplo anterior muestra cómo un simple tipo de error personalizado. Pero si necesitamos error más sofisticado manejarlo? En este punto, tenemos que hacer referencia al enfoque de red paquete:
9393

9494
package net
9595

@@ -100,7 +100,7 @@ The above example shows how a simple custom Error type. But if we need more soph
100100
}
101101

102102

103-
Place the call through the type assertion err is not net.Error, to refine error handling , such as the following example , if a temporary error occurs on the network , it will sleep 1 seconds Retry :
103+
Ponga la llamada a través de la afirmación de err tipo no es net.Error, para refinar el manejo de errores, como el siguiente ejemplo, si se produce un error temporal en la red, se va a dormir 1 segundo de reintento:
104104

105105
if nerr, ok := err.(net.Error); ok && nerr.Temporary() {
106106
time.Sleep(1e9)
@@ -110,11 +110,11 @@ Place the call through the type assertion err is not net.Error, to refine error
110110
log.Fatal(err)
111111
}
112112

113-
## Error handling
113+
## El manejo de errores
114114

115-
Go in the error handling on the use of the C check the return value similar manner , rather than most other mainstream languages used in unexpected ways , which caused a code written on a big disadvantage : error handling code redundancy , for this kind of situation is that we detect function to reduce reuse similar code .
115+
Ve en el manejo de errores en el uso de la C comprobar el valor devuelto de manera similar, en lugar de la mayoría de los otros idiomas principales utilizados de maneras inesperadas, lo que causó un código escrito en una gran desventaja: el manejo de errores de código de redundancia, para este tipo de situación es que detectamos función para reducir la reutilización de código similar.
116116

117-
Look at the following example code:
117+
Mira el siguiente código de ejemplo:
118118

119119
func init() {
120120
http.HandleFunc("/view", viewRecord)
@@ -133,7 +133,7 @@ Look at the following example code:
133133
}
134134
}
135135

136-
The above example shows a template to get data and call has detected an error when an error occurs , call a unified processing function `http.Error`, returned to the client 500 error code and display the corresponding error data . But when more and more HandleFunc joined, so that error-handling logic code will be more and more, in fact, we can customize the router to reduce the code ( realization of the ideas you can refer to Chapter III of the HTTP Detailed ) .
136+
El ejemplo anterior muestra una plantilla para obtener los datos y la llamada se ha detectado un error cuando se produce un error, llamar a una función de procesamiento unificado http.Error , devuelve al cliente 500 código de error y mostrar los datos de error correspondientes. Pero cuando más y más HandleFunc unió, para que el código de lógica de manejo de errores será cada vez más, de hecho, podemos personalizar el router para reducir el código (realización de las ideas se puede hacer referencia al Capítulo III del HTTP detallado).
137137

138138
type appHandler func(http.ResponseWriter, *http.Request) error
139139

@@ -143,13 +143,13 @@ The above example shows a template to get data and call has detected an error wh
143143
}
144144
}
145145

146-
Above we defined a custom router , and then we can adopt the following approach to registration function :
146+
Arriba hemos definido un enrutador personalizado, y luego podemos adoptar el siguiente enfoque de función de registro:
147147

148148
func init() {
149149
http.Handle("/view", appHandler(viewRecord))
150150
}
151151

152-
When requested `/view` when we can become as logical processing code, and the first implementation has been compared to a lot simpler .
152+
Cuando así lo solicite `/view` cuando podemos llegar a ser código de procesamiento como lógica, y la primera aplicación ha sido comparado con una mucho más simple..
153153

154154
func viewRecord(w http.ResponseWriter, r *http.Request) error {
155155
c := appengine.NewContext(r)
@@ -161,15 +161,15 @@ When requested `/view` when we can become as logical processing code, and the fi
161161
return viewTemplate.Execute(w, record)
162162
}
163163

164-
The above example error handling when all errors are returned to the user 500 error code, and then print out the corresponding error code , in fact, we can put this definition more friendly error messages when debugging is also convenient positioning problem, we can custom return types of errors :
164+
El ejemplo anterior gestión de errores cuando los errores se devuelven al usuario 500 código de error, y luego imprimir el código de error correspondiente, de hecho, podemos poner esta definición los mensajes de error más amigables al depurar también es conveniente un problema de posicionamiento, podemos volver personalizada tipos de errores:
165165

166166
type appError struct {
167167
Error error
168168
Message string
169169
Code int
170170
}
171171

172-
So that our custom router can be changed as follows :
172+
Así que nuestro router personalizado puede ser cambiado de la siguiente manera:
173173

174174
type appHandler func(http.ResponseWriter, *http.Request) *appError
175175

@@ -181,7 +181,7 @@ So that our custom router can be changed as follows :
181181
}
182182
}
183183

184-
Such custom error after modifying our logic can be changed as follows :
184+
Tal error personalizado después de modificar nuestra lógica se puede cambiar de la siguiente manera:
185185

186186
func viewRecord(w http.ResponseWriter, r *http.Request) *appError {
187187
c := appengine.NewContext(r)
@@ -196,11 +196,11 @@ Such custom error after modifying our logic can be changed as follows :
196196
return nil
197197
}
198198

199-
As shown above, in our view when you can visit according to different situations for different error codes and error messages , although this first version of the code and the amount is almost, but this show is more obvious error , the error message prompts more friendly , scalability is also better than the first one .
199+
Como puede observarse, en nuestra opinión, cuando se puede visitar de acuerdo a las diferentes situaciones de los diferentes códigos de error y mensajes de error, aunque esta primera versión del código y la cantidad es casi, pero este espectáculo es el error más obvio, el mensaje de error le pide más amigable , la escalabilidad es también mejor que el primero.
200200

201-
## Summary
201+
## Resumen
202202

203-
In programming , fault tolerance is a very important part of the work , in Go it is achieved through error handling , error although only one interface, but it can have many variations but we can according to their needs to achieve different treatment Finally introduce error handling scheme , we hope that in how to design better programs on the Web error handling to bring some ideas .
203+
En la programación, la tolerancia a fallos es una parte muy importante de la obra, en el Go es logrado a través de la gestión de errores, el error aunque sólo una interfaz, pero puede tener muchas variaciones, pero podemos de acuerdo a sus necesidades para lograr un tratamiento diferente introducir último tratamiento de errores esquema, esperamos que en la forma de diseñar mejores programas en el manejo de errores Web para traer algunas ideas.
204204

205205
## Links
206206

0 commit comments

Comments
 (0)