【问题标题】:Can't get 400 Bad request properly无法正确获得 400 Bad request
【发布时间】:2019-10-22 14:51:08
【问题描述】:

我正在尝试处理用户身份验证错误,当用户注册新帐户但用户名已经存在时,它应该抛出 400 Bad request 错误。

这是我在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,它将在 fetch 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 组件中的 register 方法将在控制台上显示错误,除了AuthController 的 register 方法中定义的 400 Bad 请求之外,一切都按我的预期工作。现在它返回“服务器错误”,但我期望的是“用户名已经存在!”

我使用的是 .net-core 2.2,对 Angular 来说是全新的。我将不胜感激任何帮助我解决这个问题的想法:-)

【问题讨论】:

  • 是的,但我已经处理了 400 状态,返回字符串“用户名已经存在!”所以我希望角度应用程序的控制台返回相同的字符串,而不是“服务器错误”,这是一些未处理的异常。
  • 在你的拦截器中,在此之前 if (error instanceof HttpErrorResponse) 请尝试执行 console.log(error ) 并查看 HTTP 状态
  • 是的,我可以在 HttpErrorResponse 中找到错误字符串“用户名已存在”
  • 所以这里你现在那里,这就是原因 => return throwError(modalStateErrors || serverError || ''Server Error'');
  • 尝试将其更改为返回 throwError(modalStateErrors || serverError || error.error );

标签: angular .net-core


【解决方案1】:

修改代码后,

由于return语句,问题出在interceptor,已通过以下方式解决:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-26
    • 1970-01-01
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-25
    相关资源
    最近更新 更多