我有ErrorInterceptor,它从.net核心2.2后端获取错误消息。对于单个消息,它正确地显示了消息,但是对于多条消息,它失败了。
My ErrorInterceptor.ts :
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
catchError(err => {
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
return throwError(err.statusText);
}
const applicationError = err.headers.get('Application-Error');
if (applicationError) {
console.error(applicationError);
return throwError(applicationError);
}
const serverError = err.error;
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');
}
})
)
}
}
export const ErrorInterceptorProvide = {
provide: HTTP_INTERCEPTORS,
useClass: ErrorInterceptor,
multi: true
}用于单个错误的json文件示例,该文件显示正确的消息:
"Username already exists"多个错误消息的例子,我想从json中提取错误,而不是标题和其他任何东西。准确地说,错误内部的错误信息。我正在使用警报显示这条信息。Json结果:
{"errors":{"Password":["password is required"],"Username":["username is required"]},"title": "One or
more validation errors occurred.","status":400,"traceId":"0HLRU5MDVJPEI:00000004"}如何显示准确的错误信息?
发布于 2019-12-11 12:04:11
由于您的错误消息驻留在errors属性上,而错误驻留在数组上,所以您可以尝试以下代码。
if (serverError && typeof serverError === 'object') {
const errors = serverError.errors;
for (const key in errors) {
if (Array.isArray(errors[key])) {
modalStateErrors += errors[key].join('\n');
}
}
}
https://stackoverflow.com/questions/59285328
复制相似问题