Skip to content

Latest commit

 

History

History
141 lines (105 loc) · 10.1 KB

File metadata and controls

141 lines (105 loc) · 10.1 KB

12.2 Errors and crashes

Our on-line soon after the Web application, then the probability of various error has occurred, Web applications may be a variety of daily operation errors, specifically as follows:

  • Database error: refers to access the database server or data -related errors. For example, the following may occur some database errors.

  • Connection Error: This type of error may be disconnected from the network database server, user name, password is incorrect, or the database does not exist.

  • Query Error: illegal use of SQL cause an error like this SQL error if the program through rigorous testing should be avoided.

  • Data Error: database constraint violation, such as a unique field to insert a duplicate primary key values ​​will complain, but if your application on-line through a rigorous testing before also avoid such problems.

  • Application Runtime Error: This type of error range is very wide, covering almost all appear in the code error. Possible application errors are as follows:

  • File system and permissions: application to read the file does not exist, or do not have permission to read the file, or written to a file is not allowed to write, which will result in an error. If the application reads the file format is not correct will be given, such as configuration files should be INI configuration format, and set into JSON format an error.

  • Third-party applications: If our application interfaces coupled with other third-party programs, such as articles published after the application automatically calls the hair micro-blogging interface, so the interface must be running to complete the function we publish an article.

  • HTTP errors: These errors are based on the user's request errors, the most common is the 404 error. While there may be many different errors, but also one of the more common error 401 Unauthorized error( authentication is required to access the resource ), 403 Forbidden error( do not allow users to access resources ) and 503 error( internal program error ).

  • Operating system error: These errors are due to the application on the operating system error caused mainly operating system resources are allocated over, leading to crashes, as well as the operating system disk is full, making it impossible to write, so it will cause a lot of errors.

  • Network error: error refers to two aspects, one is the application when the user requests a network disconnection, thus disrupt the connection, this error does not cause the application to crash, but it will affect the effect of user access ; another on the one hand is an application to read the data on other networks, other network disconnect can cause read failures, such an application needs to do effective testing, to avoid such problems arise in case the program crashes.

Error processing of the target

Error handling in the realization, we must be clear error handling is what you want to achieve, error handling system should accomplish the following tasks:

  • Notification access user errors: the matter is that a system error occurs, or user error, the user should be aware Web applications is a problem, the user 's current request could not be completed correctly. For example, a request for user error, we show a unified error page(404.html). When a system error occurs, we passed a custom error page display system is temporarily unavailable kind of error page(error.html).
  • Record error: system error, generally what we call the function to return the case err is not nil, you can use the front section describes the system log to a log file. If it is some fatal error, the system administrator is notified via e-mail. General 404 such mistakes do not need to send messages to the log system only needs to record.
  • Rollback the current request: If a user requests occurred during a server error, then the need to roll back the operation has been completed. Let's look at an example: a system will save the user submitted the form to the database, and to submit this data to a third-party server, but third-party server hung up, which resulted in an error, then the previously stored form data to a database should delete( void should be informed ), and should inform the user of the system error.
  • Ensure that the existing program can be run to serve: We know that no one can guarantee that the program will be able to have a normal running, if one day the program crashes, then we need to log the error, and then immediately let the program up and running again, let the program continue to provide services, and then notify the system administrator through the logs to identify problems.

How to handle errors

Error Handling In fact, we have eleven chapters in the first section which has been how to design error handling, here we have another example from a detailed explanation about how to handle different errors:

  • Notify the user errors:

Notify the user when accessing the page we can have two kinds of errors: 404.html and error.html, the following were the source of the error page displays:

<html lang="en">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Page Not Found
  </title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

<body>
  <div class="container">
	<div class="row">
	  <div class="span10">
		<div class="hero-unit">
		  <h1> 404! </h1>
		  <p>{{.ErrorInfo}}</p>
		</div>
	  </div>
	  <!--/span-->
	</div>
  </div>
</body>

</html>

Another source:

<html lang="en">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>system error page
  </title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

</head>

<body>
  <div class="container">
	<div class="row">
	  <div class="span10">
		<div class="hero-unit">
		  <h1> system is temporarily unavailable ! </h1>
		  <p>{{.ErrorInfo}}</p>
		</div>
	  </div>
	  <!--/span-->
	</div>
  </div>
</body>

</html>

Error handling logic 404, an error if the system operation is similar, and we see that:

func (p *MyMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path == "/" {
		sayhelloName(w, r)
		return
	}
	NotFound404(w, r)
	return
}

func NotFound404(w http.ResponseWriter, r *http.Request) {
	log.Error(" page not found")              //error logging
	t, _ = t.ParseFiles("tmpl/404.html", nil) //parse the template file
	ErrorInfo := " File not found "           //Get the current user information
	t.Execute(w, ErrorInfo)                   //execute the template merger operation
}

func SystemError(w http.ResponseWriter, r *http.Request) {
	log.Critical(" System Error")                      //system error triggered Critical, then logging will not only send a message
	t, _ = t.ParseFiles("tmpl/error.html", nil)        //parse the template file
	ErrorInfo := " system is temporarily unavailable " //Get the current user information
	t.Execute(w, ErrorInfo)                            //execute the template merger operation
}

How to handle exceptions

We know that in many other languages ​​have try... catch keywords used to capture the unusual situation, but in fact, many errors can be expected to occur without the need for exception handling, should be handled as an error, which is why the Go language using the function returns an error of design, these functions do not panic, for example, if a file is not found, os.Open returns an error, it will not panic; if you break the network connection to a write data, net.Conn series Type the Write function returns an error, they do not panic. These states where such procedures are to be expected. You know that these operations might fail, an error is returned because the designer has used a clear indication of this. This is the above stated error can be expected to occur.

But there is a situation, there are some operations almost impossible to fail, and in certain cases there is no way to return an error and can not continue, such a situation should panic. For example: if a program to calculate x [j], but j bounds, and this part of the code will lead to panic, like this one unexpected fatal error will cause panic, by default it will kill the process, it this allows a part of the code that is running from the error occurred panic goroutine recover operation, the occurrence of panic, the function of this part of the code and the code behind not be executed, which is specially designed such that Go, as separate from the errors and abnormal, panic fact exception handling. The following code, we expect to get the User via uid the username information, but if uid crossed the line will throw an exception, this time if we do not recover mechanism, the process will be killed, resulting in non- service program. So in order to process robustness, in some places need to establish recover mechanism.

func GetUser(uid int) (username string) {
	defer func() {
		if x := recover(); x != nil {
			username = ""
		}
	}()

	username = User[uid]
	return
}

The above describes the difference between errors and exceptions, so when we develop programs how to design it? The rules are simple: If you define a function may fail, it should return an error. When I call other package 's function, if this function is implemented well, I do not need to worry that it will panic, unless there is a true exception to happen, nor even that I should go with it. The panic and recover for its own development package which implements the logic to design for some special cases.

Summary

This section summarizes when we deployed Web application how to handle various error: network error, database error, operating system errors, etc., when an error occurs, our program how to correctly handle: Show friendly error interface, rollback, logging, notify the administrator and other operations, and finally explains how to correctly handle errors and exceptions. General program errors and exceptions easily confused, but errors and exceptions in Go is a clear distinction, so tell us in a program designed to handle errors and exceptions should follow the principles of how to.

Links