[英]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 状态代码
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.