繁体   English   中英

如何在Fetch Api中分别处理返回不同的http状态码?

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

我正在向后端发送请求,但后端可以返回不同的状态代码,如下所示:

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);
                }
            }
    }

我的 fetch 方法调用的以前版本是:

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")});
 }

我想做的是根据响应的状态代码处理不同的响应,例如:

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

我该如何处理?

您可以执行以下操作,

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")});
}

旁注:您可以使用HTTP拦截器在中心位置处理所有 http 状态代码

response object 有一个属性状态,它是服务器返回的 http 状态代码。

您可以在响应属性中查看 HTTP 状态。

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

知道您可以在 if 语句中访问 response.status 并进行比较。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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