简体   繁体   中英

How to handle returned different http status codes separately in Fetch Api?

I am sending a request to backend but backend can return different status codes as below:

public ResponseEntity<UserDto> loginUser(@RequestBody UserDto userDto) {
        User userObj;
            if (isNull(userDto.getEmail()) || isNull(userDto.getPassword())) {
                return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
            }
            else {
                try {
                    userObj = userService.getUserByEmailAndPassword(userDto);
                    if (isNull(userObj)) {
                        return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
                    }
                    return ResponseEntity.ok(modelMapper.map(userObj, UserDto.class));
                } catch (Exception e) {
                    return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
                }
            }
    }

And previous version of my fetch method call is:

async loginUser() {
  let response = await this._service.loginUser(this.user)
  .then(response => {return response.json()})
  .then(response => {
    if (response.error) {
      this.dialog.open(ErrorDialogComponent);
  } else {
    this._router.navigate(['/mainpage'], {queryParams: {userId: response.userId}})
  }
  })
  .catch(error => {alert("Something went wrong")});
 }

What I want to do es handling the response different according the status code of the response something like:

async loginUser() {
      let response = await this._service.loginUser(this.user)
      .then(response => {return response.json()}).
then if status code is 401 (do this)
then if status code is 500 (do this)
.
.
etc

How can i handle it?

You can implement something as below,

export enum STATUSCODE{

     NOTFOUND= 401,
     ERROR = 500,
     ...
}
    
async loginUser() {
      let response = await this._service.loginUser(this.user)
      .then(response => {return response.json()})
      .then(response => {
     
        ...
        ...

        switch (response.status)) {
           case STATUSCODE.NOTFOUND: // do something here
                     break;
           case STATUSCODE.ERROR: // do something here
                     break;
        }
        
        ...
        ...
      })
      .catch(error => {alert("Something went wrong")});
}

Side Note : You can handle all http status codes at central place using HTTP Interceptor

The response object has a property status which is the http status code returned by the server.

You can see HTTP-status in the response properties.

status – HTTP status code, e.g. 200.
ok – boolean, true if the HTTP status code is 200-299.

Knowing that you can access response.status in your if statement and compare it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM