Я хочу перехватить сообщение об ошибке вместо имени ошибки.
В настоящее время используется перехватчик в 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);
}))
}
}
Но он возвращает только «Плохой запрос» вместо сообщения об ошибке от 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");
}
}





Это решение проблемы, а не:
const error = err.error.message || err.statusText;
Я использовал другую трубу:
const error = err.error.message || err.error;
Как правило, вам не нужно использовать API низкого уровня, например HttpInterceptor, поскольку HttpClient уже предоставил адекватные функции для обработки ошибок HTTP.
Клиентская служба 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' });
}
В вашем коде приложения:
this.service.addRole(this.userId, roleName)
.pipe(takeWhile(() => this.alive))
.subscribe(
(data) => {
//handle your data here
},
(error) => {
error(error);
}
Подробнее об обработке ошибок:
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
}
И вы можете перейти к деталям HttpErrorResponse, чтобы более точно обрабатывать ошибки.