Skip to content

Commit

Permalink
traduccion capitulo 11
Browse files Browse the repository at this point in the history
  • Loading branch information
carlosjml4 committed Jun 16, 2014
1 parent eaa65c5 commit 806c377
Show file tree
Hide file tree
Showing 5 changed files with 116 additions and 118 deletions.
12 changes: 6 additions & 6 deletions eBook/11.0.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
# 11 Error Handling, Debugging, and Testing
# 11 Manejo de errores, depurar y probar

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.
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.

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.
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.

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.
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.

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.
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.

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.
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.

## Links

Expand Down
56 changes: 28 additions & 28 deletions eBook/11.1.md
Original file line number Diff line number Diff line change
@@ -1,27 +1,27 @@
# 11.1 Error handling
# 11.1 La gestión de errores

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
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

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

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 :
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::

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

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.
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.

## Error type

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

type error interface {
Error() string
}

`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
`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

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

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:
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:

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

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

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

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 :
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:

f, err := Sqrt(-1)
if err != nil {
fmt.Println(err)
}

## Custom Error
## Error Custom

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:
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:

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

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

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:
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:

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

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:
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:

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

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

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:
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:

package net

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


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 :
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:

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

## Error handling
## El manejo de errores

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 .
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.

Look at the following example code:
Mira el siguiente código de ejemplo:

func init() {
http.HandleFunc("/view", viewRecord)
Expand All @@ -133,7 +133,7 @@ Look at the following example code:
}
}

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 ) .
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).

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

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

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

func init() {
http.Handle("/view", appHandler(viewRecord))
}

When requested `/view` when we can become as logical processing code, and the first implementation has been compared to a lot simpler .
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..

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

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 :
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:

type appError struct {
Error error
Message string
Code int
}

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

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

Expand All @@ -181,7 +181,7 @@ So that our custom router can be changed as follows :
}
}

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

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

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 .
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.

## Summary
## Resumen

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 .
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.

## Links

Expand Down
Loading

0 comments on commit 806c377

Please sign in to comment.