简体   繁体   English

Angular + Core API:如何拦截请求响应错误正文

[英]Angular + Core API: How to intercept request response error body

I want to intercept the error message instead of the error name. 我想截取错误消息而不是错误名称。

Currently used interceptor in Angular: 当前在Angular中使用的拦截器:

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
    constructor(private authenticationService: AuthenticationService) {}

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(catchError(err => {
            if (err.status === 401) {
                this.authenticationService.logout();
                location.reload(true);
            }               
            const error = err.error.message || err.statusText;
            return throwError(error);
        }))
    }
}

But it's returning only "Bad Request" instead of the error message from the API. 但是它仅返回“错误请求”,而不返回API的错误消息。

public IActionResult Login([FromBody]UserModel user)
{ 
    if (userRepository.CheckIfUserExists(user.Username))
    {
        if (userRepository.CheckIfPasswordIsCorrect(user))
        {
            return new JsonResult(userRepository.GetUser(user));
        }
        else
        {
            return BadRequest("Test");
        }
    }
    else
    {
        return BadRequest("Test");
    }
}

This is the solution to the problem, instead of: 这是解决问题的方法,而不是:

const error = err.error.message || err.statusText;

I used a different pipe: 我使用了不同的管道:

const error = err.error.message || err.error;

Generally you don't need to use low level API like HttpInterceptor, since HttpClient had already provided adequate functions to handle HTTP errors. 通常,您不需要使用像HttpInterceptor这样的低级API,因为HttpClient已经提供了足够的功能来处理HTTP错误。

Http client service: Http客户端服务:

export namespace My_WebApi_Controllers_Client {
@Injectable()
export class Account {
    constructor(@Inject('baseUri') private baseUri: string = location.protocol + '//' + location.hostname + (location.port ? ':' + location.port : '') + '/', private http: HttpClient) {
    }

    /**
     * POST api/Account/AddRole?userId={userId}&roleName={roleName}
     */
    addRole(userId: string, roleName: string): Observable<HttpResponse<string>> {
        return this.http.post(this.baseUri + 'api/Account/AddRole?userId=' + encodeURIComponent(userId) + '&roleName=' + encodeURIComponent(roleName), null, { observe: 'response', responseType: 'text' });
    }

In you app code: 在您的应用代码中:

            this.service.addRole(this.userId, roleName)
            .pipe(takeWhile(() => this.alive))
            .subscribe(
            (data) => {
                //handle your data here
            },
            (error) => {
                error(error);
            }

Error handling in details: 错误处理的详细信息:

    error(error: HttpErrorResponse | any) {
            let errMsg: string;
    if (error instanceof HttpErrorResponse) {
        if (error.status === 0) {
            errMsg = 'No response from backend. Connection is unavailable.';
        } else {
            if (error.message) {
                errMsg = `${error.status} - ${error.statusText}: ${error.message}`;
            } else {
                errMsg = `${error.status} - ${error.statusText}`;
            }
        }

        errMsg += error.error ? (' ' + JSON.stringify(error.error)) : '';
    } else {
        errMsg = error.message ? error.message : error.toString();
    }
    //handle errMsg

}

And you may go to the details of HttpErrorResponse to handle errors more specifically. 您可以转到HttpErrorResponse的详细信息以更具体地处理错误。

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

相关问题 cefsharp如何截获xhr请求以获取响应正文值? - how can cefsharp intercept xhr request to obtain response body value? 如何在Dotnet Core中拦截请求令牌Jwt发送到其他API? - How to intercept request Token Jwt in Dotnet Core to Send to other API? 使用ASP.NET核心中间件拦截API响应(错误代码:403) - Intercept API Response(Error code: 403) using a ASP.NET Core Middleware 拦截和修改请求体 - Intercept and modify request body 如何在 Web API 请求和响应主体的帮助页面中显示参数 - How to display parameter in Web API help page for request and response body 如何在asp.net core(Kestrel)中记录http请求消息(非正文)和响应消息(非正文) - how to log http request message(not body) and response message(not body) in asp.net core(Kestrel) 如何使用 Angular 取消 .Net Core Web API 请求? - How to cancel .Net Core Web API request using Angular? 核心 Web Api - 错误:操作从请求正文绑定了多个参数 - Core Web Api - Error: Action has more than one parameter bound from request body MVC 3 API自定义响应主体出现错误 - MVC 3 API custom response body on error ASP.NET Core Web API + Angular 对预检请求的响应未通过访问控制检查:预检请求不允许重定向 - ASP.NET Core Web API + Angular Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM