Search code examples
javascriptangularhttprequestfetch-api

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 ?


Solution

  • 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