Now, many projects are Web projects where the front and back ends are separated and the only interaction is through restful interfaces. How does status code return when we request it back?

First, the HTTP status code is introduced.

2XX(Success Status code)

200 – OK

The request is successful

201 – Created

Document creation is successful, such as adding a user successfully

202 – Accepted

The request has been accepted, but the action may not have been completed. This is used for background operations, such as asynchronous operations such as database compression

4XX(Client Error Client Error status code)

400 – Bad Request

Request parameters are wrong (e.g., you should pass a Number parameter, but you pass a string), the request cannot be understood by the server, you can resubmit the request after modification

401 – Unauthorized

The current requesting user is not authorized, for example, not logged in

403 – Forbidden

The current request was rejected. For example, there is a problem with file system access or an unauthorized operation (such as a common user trying to get the admin user list).

404 – Not Found

The requested resource could not be found, usually due to a URL error

405 – Method Not Allowed

The requested URL was requested using an invalid HTTP request type. For example, an API only supports POST, while a client uses GET

406 – Not Acceptable

The server does not support the requested content Type

413 – Request Entity Too Large

If the request body is too large, it is not supported. Usually, the uploaded file exceeds the limit.

5XX(Server Error Server Error status code)

500 – Internal Server Error

Indicates that a server error occurred while executing the request. There may be a bug in the server or application

503 – Service Unavailable

The service is unavailable and cannot process the request at this time.

What error code is returned

Generally, in restful apis, we recognize status codes as follows:

2xx: The server can execute the request received from the client. 4xx: The server cannot execute the request because the client sends incorrect data. (After the client corrects the error, the server can send another request.) The client sent the data correctly, but the server failed to execute the data.

But I’ve also seen status code return 200 and then a custom code in Response tells the user whether the request was successful or not

{

  "code"10020.

  "msg""Name cannot be empty"

}

Copy the code

I personally believe that for REST interfaces, status at the HTTP level should be used to indicate success. Because network communication is more than a client-server affair, there are many layers of nodes in between, and if one of these layers has a very orthodox understanding of status 200 requests and does caching or something, you may be stuck. And since it is to write the interface, it is best to standard a bit, do not bury a hole for yourself.

So for a successful request you should return 2XX, and for a 4XX interface you can encapsulate it

Return the data

The status code must return 4XX, but you can return the exception error code in Reponse data (the error code is the error code of the business error), at this time can agree with the front end of the business error code represents what meaning, you can give the user the corresponding prompt.

The format of the data returned

public class BaseResponse<T{



    // Service exception code

    private int code;



    // Description information

    private String msg;



    // The returned data needs to be encapsulated

    private T data;

}

Copy the code

For example, for GET/API/Users /1, the data returned by such a request is placed in the data field.

{

  "code":200.

  "msg":"SUCCESS".

  "data": {

    "id":1095.

    "name":"Zhang"

  }

}

Copy the code

For failed requests (HTTP status code 4XX), the following data is returned

{

  "code"10030.

  "msg"Id does not exist

}

Copy the code

Spring’s support for Http Status Code

@ResponseStatus(HttpStatus.CREATED)

public BaseResponse addUser(UserParam userParam) {



    return service.addUser(userParam);

}

Copy the code

You can specify the error code to be returned directly via the ResponseStatus annotation. Of course, the above is the normal situation, which parameters fail verification failure or other service exceptions caused by the situation how to deal with?

There are two ways to do this. The first is through Spring’s ResponseEntity class

public ResponseEntity<BaseResponse> addUser(UserParam userParam) {



  if(validate(userParam)) {

      return service.addUser(userParam);

  }



  return  new ResponseEntity<>(ResponseUtil.fail(STATUS_INVALID_PARAM), HttpStatus.NOT_FOUND);

}

Copy the code

The second approach is to use global exception handling. If there is a problem with the parameters passed by the client in the service, you can throw an exception and then handle it uniformly in the global exception interceptor

@RestControllerAdvice

public class WebExceptionConfig {



  @ExceptionHandler(InvalidParamException.class)

  @ResponseStatus(HttpStatus.BAD_REQUEST)

  public BaseResponse handleInvalidParamException(InvalidParamException e) {

      return ResponseUtil.fail(STATUS_INVALID_PARAM, e.getMessage());

  }

}

Copy the code

conclusion

  1. Different status codes are returned for different situations. For failed requests, return 4XX and specify the service exception code by returning data
  2. There must be internal unity
  3. Don’t let the status code returned affect your business logic

Pay attention and don’t get lost

If you think my writing is ok, please give me a thumbs-up, attention, share ah, it is a great incentive for me.

Public account Think123, you can read it first time.

Review past

Hey, I use Drone for CI

And the interviewer blows the MongoDB replica set like this

Knowing these MongoDB design tips increases your efficiency by 50%

I spent a week reading Kafka Producer’s source code

Interviewer: How do I implement LRU with LinkedHashMap

How do I understand Java8 Stream

I’m no longer afraid of being asked JDK8 HashMap

Timing indexes in MongoDB