preface

Recently, our company will formulate development specifications. In the discussion of interface return, the backend colleagues asked our front-end, error message return, what is the front-end opinion?

So I did some research for the reference of colleagues at the back end.

Error message returned

When using an API, it is inevitable that the interface will return the wrong message for various reasons. For example, the specified query parameter is incorrect, or method is not supported. Error messages must also be returned if the server is unstable or stopped.

Obviously, when an error occurs, it is not enough to simply return “an error occurred.” If the front end doesn’t know what’s wrong, it doesn’t know how to debug and fix the bug. Therefore, you must return as much information as possible to the front end so that the front end can find what went wrong and fix it.

The HTTP status code indicates the error message

First, you must choose the appropriate HTTP status code, which our backend API did not follow. For example, the API will return a 200 status code no matter how it is accessed, only describing whether an error occurred in the body of the returned message.

HTTP/1.1 200 OK Content-Type: Application /json {"error": {"code": 2002, "message": "Invalid parameter"}} 200 OK Content-Type: Application /json {"error": {"code": 2002, "message": "Invalid parameter"}}Copy the code

Although the front-end can understand the API error message in this way, since the HTTP protocol has fully defined the meaning of each status code, returning the appropriate status code increases the likelihood that the front-end will correctly identify the error.

If something goes wrong and still returns 200 status codes, it may lead to confusion in front-end processing, which must be prohibited. In particular, the general API basically looks at the status code first and then decides the next step of processing. If the correct status code is not returned, it will lead to the front end can not execute the appropriate method to process, resulting in a variety of unnecessary problems. Moreover, this approach does not utilize HTTP as much as possible and makes it difficult to write front-end error handling.

  • Status code classification
Status code meaning
1xx The message
2xx successful
3xx redirect
4xx Error caused by front-end cause
5xx Error caused by server

4xx and 5xx error codes:

4xx– A front-end error occurred

4XX status codes are mainly used to describe errors caused by front-end request problems, that is, there is no problem on the server side, but the server side cannot understand the front-end request, or can understand but cannot process the request. The 4XX error code is used for this type of error.

Status code The name of the instructions
400 Bad Request Represents other errors, namely front-end errors that 4XX cannot describe
401 Authentication Indicates an error in the authentication type
403 Authorization An error indicating authorization (the difference between authentication and authorization is that authentication means “identifying who is coming to access,” while authorization means “giving a specific user the right to perform a specific action.”)
404 Not Found The accessed data does not exist
405 Method Not Allowd Indicates that the interface is accessible, but the HTTP method used does not allow it
406 Not Acceptable Indicates that the API does not support the data format specified by the front end
408 Request Timeout Indicates that requests sent from the front end are taking too long to reach the server
409 Confilct Indicates that a resource is in conflict, for example, when registered with a registered email address
410 Gone The accessed resource does not exist. Not only does it indicate that the resource does not exist, it further informs the resource that the resource once existed but is now gone
413 Request Entity Too Large Represents an error caused by the request message body being too long
414 Request-URI Too Large Indicates an error caused by the request header being too long
415 Unsupported Media Type Indicates that the server does not support the data format specified in the content-Type header of the client request
416 Range Not Satisfiable Indicates that the package body specified in the Range request cannot be supplied
417 Expectation Failed Represents the response code when the expected condition of the Expect request header cannot be met
421 Misdirected Request Indicates that the server thinks the request should not be sent to it because it cannot handle it
426 Upgrade Required Indicates that the server refuses to provide services based on the current HTTP protocol. The Upgrade header informs the client that the protocol must be upgraded to continue processing
428 Precondition Required Indicates that a condition class header, such as if-match, is missing in the user request
429 Too Many Requests The rate at which the client sends requests is too high
431 Request Header Fields Too Large Indicates that the HEADER size of the request is out of the limit
451 Unavailable For Legal Reasons Indicates that it is inaccessible for legal reasons

5xx– An error occurs on the server

The 5XX status code indicates that the error was caused by a server-side problem.

Status code The name of the instructions
500 Internal Server Error Indicates an internal server error that does not fall into the following error types
501 Not Implemented Indicates that the server does not support the functionality required to implement the request
502 Bad Gateway The proxy server cannot obtain valid resources
503 Service Unavailable The server resources are not ready to handle the current request
504 Gateway Timeout Indicates that the proxy server cannot get a response from the upstream in a timely manner
505 HTTP Verson Not Supported The HTTP version used in the request is not supported
507 Insufficient Storage Indicates that the server does not have enough space to process the request
508 Loop Detected Indicates that a loop was detected while accessing a resource
511 Network Authentication Required Indicates that the proxy server discovers that the client requires authentication to obtain network access permission

The forward end returns detailed error information

When an error occurs, you need to return a detailed error message in addition to the corresponding status code. Because a status code is a generic error description, it cannot represent the actual error information.

For example, with the 400 status code, you just know that there is an error in the front-end request. As for how to fix it, this is not the only way to find the bug.

In general, there are two ways to return an error message:

  • Put information inHTTPResponse headers
  • Get the information throughHTTPResponse body return

1. Put detailed error information into the response header by customizing headers

X-ERROR-CODE: 2020
X-ERROR-MESSAGE: Bad authentication token
X-ERROR-INFO: http://api.example.com/v1/authentication
Copy the code

2. Place the error message in the response body

{
	"error": {
    	"code": 2020."message": "Bad authentication token"."info": "http://api.example.com/v1/authentication"}}Copy the code

From the front end, returning through the response body is easier to handle.

The name of the error code here can be written according to the requirements of the backend.

In general, the interface error information is required to be as detailed as possible, but this is not always the case, and there may be special cases. Generally speaking, the front-end will display the error message of the back-end interface intact, because it is difficult for the front-end to determine whether there is confidential information or embarrassing information. For example, if user A blocks user B, when user B wants to see user A’s details, if the correct return: “User A has blocked user B, can not obtain”, it will embarrass both parties. This is where ambiguous information needs to be returned. This is something backend developers need to figure out for themselves.

For default returns andAPImaintenance

Some interfaces return HTML in the event of an error. This is especially true when 404, 503 and other errors occur. When these errors occur, the Web server or app framework used to build the API returns an error message directly, mostly in HTML by default.

But despite the error, the front end is still being accessed, so you still expect the server to return the agreed format, such as JSON. This is especially true if the receive format is specified through the Accept request header or extension, etc. You can, of course, have the front end examine the Content_Type header and process it accordingly. However, if the front end is not handled well or not handled, the app may crash.

A public API, in particular, is not a good API because you can’t expect all users to follow the specification strictly.

In terms of API maintenance, it is normal to avoid having to stop API occurrences. In this case, 503 status code is returned to inform the front-end that the CURRENT API has stopped working. Also, because this stop is not accidental but planned, you need to have information about when the API will restart and send it to the front end.

Not only should you have status codes and error messages returned for regular maintenance, but you should also use retry-after headers to tell the front end when maintenance will end. From an SEO point of view, this approach is also applicable to the maintenance of ordinary Web sites and is recommended by Google.

The retry-after value can be a specific date or the number of seconds from the current moment until normal access is available.

503 Service Temporarily Unavailable
Retry-After: Mon, 9 Sep 2020 20:00:00 GMT 
Copy the code

From a front-end implementation perspective, when a 503 error is returned, the expectation is that the front end will recognize that the API’s retry-after value will wait for the specified amount of time and then call again when the API restarts.

Although these processes depend on the implementation of the front end and the back end has no control over them, it is important to return as much detailed information as possible to facilitate front-end processing and improve the user experience.

conclusion

There are three pain points:

  • You have to choose the right oneHTTPStatus code
  • The forward end returns detailed error information
  • For default returns andAPImaintenance

At the end

For more articles, please go to Github, if you like, please click star, which is also a kind of encouragement to the author.