简体   繁体   English

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

[英]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:我的 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")});
 }

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旁注:您可以使用HTTP拦截器在中心位置处理所有 http 状态代码

The response object has a property status which is the http status code returned by the server. response object 有一个属性状态,它是服务器返回的 http 状态代码。

You can see HTTP-status in the response properties.您可以在响应属性中查看 HTTP 状态。

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.知道您可以在 if 语句中访问 response.status 并进行比较。

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

相关问题 如何使用JS提取正确处理400(或任何不成功的状态代码) - How to properly handle a 400 (or any non-successful status codes) with JS fetch 如何实现 ExpressJS 错误处理,以便针对不同的 HTTP 状态码显示不同的错误 - How to implement ExpressJS Error Handling so that it shows different errors for different HTTP Status codes 处理不同的变量以获取 api - Handle different variables for fetch api 如何在 fetch api 中处理 HTTP 代码 4xx 响应 - How to handle HTTP code 4xx responses in fetch api 如何在Node中解析HTTP状态代码? - How to parse HTTP status codes in Node? http fetch 提供的状态与网络不同? - http fetch gives different status than network? 为什么我不能处理从 $.ajax 返回的 HTTP 状态代码? - Why can't I process the returned HTTP status codes from $.ajax? 使用 fetch(),从非 HTTP OK 状态码读取响应体并捕获异常 - Use fetch(), read response body from non HTTP OK status codes and catch the exception 在转换为json之前反应本机访存api检查http状态 - react native fetch api check http status before converting to json 提取API-然后在两者中获取json主体,并捕获块以获取单独的状态代码 - Fetch api - getting json body in both then and catch blocks for separate status codes
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM