English
Problem Details on the client
Step 1. From an error response to a message
Why. Every failure of the API is an application/problem+json body (topic 12): a status, a stable machine-readable code such as user_name_taken, a title or detail, and for validation errors an errors dictionary keyed by field. The client needs three things from it:
- one sentence for the user for any failed request — preferably a friendly text chosen by the client for a known code, otherwise the server's own words;
- the errors of one form field, to show them under the right input (topic 17);
- a network failure (the server is down, the Wi-Fi is off) explained as such, not as "Something went wrong".
HttpClient reports every non-2xx response and every network failure as an HttpErrorResponse. Its error property holds the parsed body — or null when there was no response at all, in which case status is 0.
Do. Create the helper functions:
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)accepts anything acatchcan receive.unknownis TypeScript's safe "any": it must be narrowed before use, here withinstanceof HttpErrorResponseandtypeof … === 'string'checks.- Field names are camel-cased:
UserNamebecomesuserName. ASP.NET Core's validation names fields after the C# properties; the client's forms use camelCase names, as the JSON does. FRIENDLYis aRecord<string, string>— a dictionary — from error codes to sentences. It is the single place where the client words the API's errors; the codes are those of the*Errorsclasses of topics 7–11.problemMessagepicks, in order: the friendly text, the network message for status 0, the server'sdetail, the first field error, thetitle, a generic sentence.fieldErrors(error, 'newPassword')returns the messages of one field, or an empty array.
Step 2. The first spec
Why. problem.ts is pure logic — a function from an input to an output — and therefore the easiest code to test: no injector, no HTTP, no DOM. It is a good place to meet the shape of a Vitest spec.
Do. Create the spec next to the code:
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 })builds exactly whatHttpClientwould hand to acatch, so the tests need no server.toEqualcompares structure (like Shouldly'sShouldBeEquivalentTo),toBeidentity or primitive equality,toContaina substring.- The five tests cover the five promises of the file: parsing, friendly codes, the fallback order, network failures and field errors.
Check
Run only this spec with --include:
powershell
npm test -- --watch=false --include src/app/core/api/problem.spec.ts Test Files 1 passed (1)
Tests 5 passed (5)Without --include, all 8 tests of the project pass.