无法正确收到400错误的请求

时间:2019-10-22 14:51:08

标签: angular .net-core

我正在尝试通过用户身份验证来处理错误,并且当用户注册新帐户但用户名已存在时,它应该引发400错误的请求错误。

这是我在AuthController.cs中的注册方法:

public async Task<IActionResult>Register(UserForRegisterDto 
                                                   userForRegisterDto)
    {
    userForRegisterDto.username = userForRegisterDto.username.ToLower();

        if(await _repo.UserExists(userForRegisterDto.username)) 
        {
            return BadRequest("Username already exists !");
        }

        var userToCreate = new User
        {
            Username = userForRegisterDto.username
        };

     var createdUser = await _repo.Register(userToCreate, 
                                            userForRegisterDto.password);

        return StatusCode(201);
    }

register.component.ts中:

export class RegisterComponent implements OnInit {
@Output() cancelRegister = new EventEmitter();
model: any = {};
constructor(private authService: AuthService) { }
ngOnInit() {}

register() {
    this.authService.register(this.model).subscribe(() => {
  console.log('create successed');
}, error => {  
  console.log(error);
});
}

cancel() {
   this.cancelRegister.emit(false);
    console.log('canceled');
 }
}

register.component.html中:

<form #registerForm="ngForm" (ngSubmit)="register()">
<h2 class="text-center text-primary">Sign Up</h2>
<hr>

<div class="form-group">
    <input type="text" class="form-control" required name="username" 
    [(ngModel)]="model.username" placeholder="Username">
</div>

<div class="form-group">
    <input type="password" class="form-control" required name="password" 
[(ngModel)]="model.password" placeholder="Password">
</div>

<div class="form-group text-center">
    <button class="btn btn-success" type="submit">Register</button>
    <button class="btn btn-default" type="button" 
    (click)="cancel()">Cancel</button>
</div>
</form>

要从前端发送错误,我创建了Exceptions.cs,它将在获取API的标头中保存错误:

 public static class Exceptions
{
    public static void AddApplicationError(this HttpResponse response, 
                                            string message)
    {
        response.Headers.Add("Application-Error", message);

        response.Headers.Add("Access-Control-Expose-Headers", 
                                         "Application-Error");

        response.Headers.Add("Access-Control-Allow-Origin", "*");
    }
}

为了捕获错误,我创建了error.interceptor.ts来处理从后端发送的错误:

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): 
  Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
        catchError(error => {
    if (error instanceof HttpErrorResponse) {

        const applicationError = error.headers.get('Application-Error');
                if (applicationError) {
                    console.error(applicationError);
                    return throwError(applicationError);
                }
     const serverError = error.error.errors; 

                let modalStateErrors = '';
                if (serverError && typeof serverError === 'object' ) {
                    for (const key in serverError) {
                        if (serverError[key]) {
                            modalStateErrors += serverError[key] + `\n`;
                        }
                    }
                }

    return throwError(modalStateErrors || serverError || 'Server Error');
            }
        })
    );
    }
}
//add this method to provider in app.module.ts to get everything work 
export const ErrorProvider = { 
    provide: HTTP_INTERCEPTORS,
    useClass: ErrorInterceptor,
    multi: true
};

serverError将保留所有异常,并且寄存器组件中的register方法将在控制台上显示错误,除AuthController的register方法中定义的400 Bad请求外,其他所有操作均与我预期的一样。现在,它返回“服务器错误”,但我期望的是“用户名已存在!”

我使用的是.net-core 2.2,这是角度的全新概念。任何能帮助我解决此问题的想法,我将不胜感激:-)

1 个答案:

答案 0 :(得分:1)

修改代码后,

问题归因于interceptor的return语句,该问题已通过以下方式解决:

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): 
  Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
        catchError(error => {
    if (error instanceof HttpErrorResponse) {

        const applicationError = error.headers.get('Application-Error');
                if (applicationError) {
                    console.error(applicationError);
                    return throwError(applicationError);
                }
     const serverError = error.error.errors; 

                let modalStateErrors = '';
                if (serverError && typeof serverError === 'object' ) {
                    for (const key in serverError) {
                        if (serverError[key]) {
                            modalStateErrors += serverError[key] + `\n`;
                        }
                    }
                }

    return throwError(modalStateErrors || serverError || error.error ); 
            }
        })
    );
    }
}
相关问题