Українська
Problem Details на клієнті
Крок 1. Від відповіді з помилкою до повідомлення
Навіщо. Кожна помилка API – це тіло application/problem+json (тема 12): status, стабільний машинозчитуваний code на кшталт user_name_taken, title або detail, а для помилок перевірки – словник errors за полями. З нього клієнтові потрібні три речі:
- одне речення для користувача для будь-якого невдалого запиту – бажано зрозумілий текст, який клієнт обирає для відомого коду, а інакше слова самого сервера;
- помилки одного поля форми, щоб показати їх під потрібним полем введення (тема 17);
- збій мережі (сервер недоступний, вимкнено Wi-Fi), поясненому як такий, а не як «Щось пішло не так».
HttpClient повідомляє про кожну відповідь, що не є 2xx, і кожен збій мережі як HttpErrorResponse. Його властивість error містить розібране тіло – або null, якщо відповіді не було взагалі, і тоді status дорівнює 0.
Що зробити. Створіть допоміжні функції:
ts
import { HttpErrorResponse } from '@angular/common/http';
/** The API's application/problem+json body. */
export interface Problem {
status: number;
code?: string;
title?: string;
detail?: string;
/** Validation errors by field name (camelCase). */
errors: Record<string, string[]>;
}
const FRIENDLY: Record<string, string> = {
invalid_credentials: 'Wrong user name, email or password.',
locked_out: 'Too many failed attempts. The account is locked for 15 minutes.',
user_name_taken: 'This user name is already taken.',
email_taken: 'An account with this email already exists.',
wrong_password: 'The current password is wrong.',
invalid_refresh_token: 'Your session has expired. Please sign in again.',
avatar_invalid_type: 'Avatars must be JPEG, PNG or WebP images.',
avatar_too_large: 'Avatars can be at most 5 MB.',
attachment_invalid_type: 'This file type is not allowed.',
attachment_too_large: 'This file is too large.',
attachment_empty: 'The file is empty.',
query_too_short: 'Type at least 2 characters.',
handle_taken: 'This public handle is already taken.',
unknown_users: 'Some of the selected users no longer exist.',
direct_with_self: "You can't start a direct chat with yourself.",
chat_full: 'This chat is full.',
owner_must_transfer: 'Transfer ownership to another member before leaving.',
not_a_member: 'You are not a member of this chat.',
cannot_post: 'Only admins can post in this channel.',
not_allowed: "You don't have permission to do that.",
not_sender: 'You can only edit your own messages.',
chat_not_found: 'This chat no longer exists.',
user_not_found: 'This user no longer exists.',
message_not_found: 'This message no longer exists.',
member_not_found: 'This user is not a member.',
reply_not_found: 'The message you replied to no longer exists.',
invalid_attachments: 'Some attachments could not be used. Upload them again.',
use_leave: 'Use "Leave chat" to remove yourself.',
own_role: "You can't change your own role.",
not_for_direct_chats: "Direct chats can't be changed this way.",
};
export function toProblem(error: unknown): Problem {
if (error instanceof HttpErrorResponse) {
const body = error.error && typeof error.error === 'object' ? error.error : {};
const errors: Record<string, string[]> = {};
for (const [key, messages] of Object.entries(body.errors ?? {})) {
const field = key.length ? key[0].toLowerCase() + key.slice(1) : key;
errors[field] = Array.isArray(messages) ? messages.map(String) : [String(messages)];
}
return {
status: error.status,
code: typeof body.code === 'string' ? body.code : undefined,
title: typeof body.title === 'string' ? body.title : undefined,
detail: typeof body.detail === 'string' ? body.detail : undefined,
errors,
};
}
return { status: 0, errors: {}, detail: error instanceof Error ? error.message : undefined };
}
/** A sentence to show the user for any failed request. */
export function problemMessage(error: unknown): string {
const problem = toProblem(error);
if (problem.code && FRIENDLY[problem.code]) {
return FRIENDLY[problem.code];
}
if (problem.status === 0) {
return "Can't reach the server. Check your connection.";
}
const firstFieldError = Object.values(problem.errors)[0]?.[0];
return problem.detail || firstFieldError || problem.title || 'Something went wrong. Try again.';
}
/** Validation messages for one form field, or an empty list. */
export function fieldErrors(error: unknown, field: string): string[] {
return toProblem(error).errors[field] ?? [];
}toProblem(error: unknown)приймає все, що може отриматиcatch.unknown– це безпечний «any» у TypeScript: перед використанням його треба звузити, тут – перевіркамиinstanceof HttpErrorResponseіtypeof … === 'string'.- Імена полів перетворюються на camelCase:
UserNameстаєuserName. ASP.NET Core називає поля в перевірці за властивостями C#, а форми клієнта використовують імена в camelCase, як і JSON. FRIENDLY– цеRecord<string, string>, тобто словник, із кодів помилок у речення. Це єдине місце, де клієнт формулює помилки API; коди беруться з класів*Errorsз тем 7–11.problemMessageобирає по черзі: зрозумілий текст, повідомлення про мережу для статусу 0,detailсервера, першу помилку поля,title, загальне речення.fieldErrors(error, 'newPassword')повертає повідомлення одного поля або порожній масив.
Крок 2. Перша специфікація
Навіщо. problem.ts – це чиста логіка, функція з входу у вихід, а отже, код, який найпростіше тестувати: без інжектора, без HTTP, без DOM. Це гарне місце, щоб познайомитися з формою специфікації Vitest.
Що зробити. Створіть специфікацію поруч із кодом:
ts
import { HttpErrorResponse } from '@angular/common/http';
import { fieldErrors, problemMessage, toProblem } from './problem';
function httpError(status: number, body: unknown): HttpErrorResponse {
return new HttpErrorResponse({ status, error: body });
}
describe('problem', () => {
it('reads code, detail and camel-cases field errors', () => {
const problem = toProblem(
httpError(400, {
code: 'validation_failed',
detail: 'Bad input',
errors: { UserName: ['Too short.'], password: ['Needs a digit.'] },
}),
);
expect(problem.status).toBe(400);
expect(problem.code).toBe('validation_failed');
expect(problem.errors).toEqual({ userName: ['Too short.'], password: ['Needs a digit.'] });
});
it('turns known codes into friendly text', () => {
expect(problemMessage(httpError(409, { code: 'user_name_taken' }))).toBe(
'This user name is already taken.',
);
});
it('falls back to detail, then the first field error', () => {
expect(problemMessage(httpError(400, { code: 'x', detail: 'Server says no' }))).toBe(
'Server says no',
);
expect(problemMessage(httpError(400, { errors: { title: ['Title is required.'] } }))).toBe(
'Title is required.',
);
});
it('explains network failures', () => {
expect(problemMessage(httpError(0, null))).toContain("Can't reach the server");
});
it('returns the errors of one field', () => {
const error = httpError(400, { errors: { NewPassword: ['Too weak.'] } });
expect(fieldErrors(error, 'newPassword')).toEqual(['Too weak.']);
expect(fieldErrors(error, 'other')).toEqual([]);
});
});new HttpErrorResponse({ status, error: body })будує саме те, щоHttpClientпередав би вcatch, тож тестам не потрібен сервер.toEqualпорівнює структуру (якShouldBeEquivalentToу Shouldly),toBe– тотожність або рівність примітивів,toContain– підрядок.- П’ять тестів охоплюють п’ять обіцянок файла: розбір, зрозумілі коди, порядок запасних варіантів, збої мережі й помилки полів.
Перевірка
Запустіть лише цю специфікацію з --include:
powershell
npm test -- --watch=false --include src/app/core/api/problem.spec.ts Test Files 1 passed (1)
Tests 5 passed (5)Без --include проходять усі 8 тестів проєкту.