English
Results and errors
Step 1. Exceptions or results
Why. Most operations of a messenger can fail in expected ways: the password is wrong, the handle is taken, a subscriber tries to post in a channel, the chat does not exist. These are not bugs; they are answers. The usual C# tool for failure, the exception, fits them badly:
- The signature hides them.
Task<MessageDto> SendAsync(...)says nothing about the five ways sending can fail; the caller learns about them from the documentation, or in production. - They are expensive and noisy. An exception collects a stack trace and shows up in logs and debuggers as a problem, although "wrong password" happens a hundred times a day by design.
- Mapping them to HTTP is indirect. The API would need a catch block or a middleware that knows every exception type of the business layer.
Chatex therefore splits failures in two:
- Expected failures are returned as a
Resultthat holds either the value or anError. The signatureTask<Result<MessageDto>> SendAsync(...)tells every caller: this may fail, handle it. - Bugs — a
nullwhere none can be, a broken invariant, a lost database — are still thrown. They must not be handled one by one; they end in a 500 response and a log entry.
Step 2. The error
Why. An error must serve two readers. A program — the Angular client, a test — needs something stable to compare with: a short code such as handle_taken that never changes. A person needs a sentence. And the API needs to know which HTTP status to answer with, without knowing every error of the business layer. So an error has three parts: a coarse kind, a stable code and a human message, plus optional per-field details for validation errors.
Do. Create the folder Common in Chatex.Core (delete nothing: the project is still empty since topic 2):
cs
namespace Chatex.Core.Common;
/// <summary>What went wrong, coarse enough for the Api to pick an HTTP status from it.</summary>
public enum ErrorKind
{
Validation,
NotFound,
Forbidden,
Conflict,
Unauthorized,
}
/// <summary>An expected failure. <see cref="Code"/> is stable and meant for clients; <see cref="Message"/> is for people.</summary>
public sealed record Error(ErrorKind Kind, string Code, string Message)
{
/// <summary>Per-field messages for validation errors, keyed by property name.</summary>
public IReadOnlyDictionary<string, string[]>? Details { get; init; }
public static Error Validation(string code, string message) => new(ErrorKind.Validation, code, message);
public static Error Validation(string field, string code, string message) =>
new(ErrorKind.Validation, code, message) { Details = new Dictionary<string, string[]> { [field] = [message] } };
public static Error NotFound(string code, string message) => new(ErrorKind.NotFound, code, message);
public static Error Forbidden(string code, string message) => new(ErrorKind.Forbidden, code, message);
public static Error Conflict(string code, string message) => new(ErrorKind.Conflict, code, message);
public static Error Unauthorized(string code, string message) => new(ErrorKind.Unauthorized, code, message);
}ErrorKindhas five values, each of which the API maps to one HTTP status in topic 12:Validation→ 400,Unauthorized→ 401,Forbidden→ 403,NotFound→ 404,Conflict→ 409.Erroris arecordwith a primary constructor: immutable, compared by value, printed nicely byToString()(handy in test failures).Detailsis aninit-only property: it can be set in an object initializer or awithexpression, and never changed afterwards.- Static factory methods such as
Error.NotFound(code, message)make the code read like the rule:return Error.Conflict("handle_taken", "..."). The overloadValidation(field, code, message)also fillsDetailsfor one field —[field] = [message]uses a dictionary initializer and a collection expression.
Step 3. The result
Why. A result must be cheap (services return thousands of them), impossible to misread (no "value is null but there is no error either") and pleasant to write: a service should be able to return chat; or return ChatErrors.NotFound; without wrapping either one by hand.
Do.
cs
using System.Diagnostics.CodeAnalysis;
namespace Chatex.Core.Common;
/// <summary>Outcome of an operation that returns no value: success, or an expected <see cref="Common.Error"/>.</summary>
public readonly struct Result
{
private Result(Error error) => Error = error;
public Error? Error { get; }
[MemberNotNullWhen(false, nameof(Error))]
public bool IsSuccess => Error is null;
public static Result Success => default;
public static implicit operator Result(Error error) => new(error);
public TOut Match<TOut>(Func<TOut> onSuccess, Func<Error, TOut> onFailure) =>
IsSuccess ? onSuccess() : onFailure(Error);
}
/// <summary>Outcome of an operation: a value, or an expected <see cref="Common.Error"/>. Bugs are still exceptions.</summary>
public readonly struct Result<T>
{
private readonly T? _value;
private Result(T value)
{
_value = value;
Error = null;
}
private Result(Error error)
{
_value = default;
Error = error;
}
public Error? Error { get; }
[MemberNotNullWhen(false, nameof(Error))]
public bool IsSuccess => Error is null;
public T Value => IsSuccess
? _value!
: throw new InvalidOperationException($"Result has no value; it failed with '{Error.Code}'.");
public static Result<T> Success(T value) => new(value);
public static implicit operator Result<T>(T value) => new(value);
public static implicit operator Result<T>(Error error) => new(error);
public TOut Match<TOut>(Func<T, TOut> onSuccess, Func<Error, TOut> onFailure) =>
IsSuccess ? onSuccess(_value!) : onFailure(Error);
}The type is small, but almost every line is a deliberate choice:
readonly struct— a value type, so returning a result allocates nothing on the heap;readonlyguarantees it never changes after creation.- Private constructors — the only ways to create a result are success or an error; there is no third state.
IsSuccess => Error is null— success is simply "no error".default(Result)is therefore a success, which is whatResult.Successreturns.[MemberNotNullWhen(false, nameof(Error))]tells the compiler's nullable analysis: whenIsSuccessisfalse,Erroris notnull. Afterif (!result.IsSuccess) return result.Error;there is no warning, and no!is needed.- Implicit conversions from
Tand fromErrorlet a method declared as returningResult<ChatDto>simplyreturn dto;orreturn ChatErrors.NotFound;. The conversion operators do the wrapping. Valuethrows on a failure. Reading the value of a failed result is a bug in the caller, so here an exception is right. The message names the error code, which makes such a bug easy to find.Matchtakes two functions — one for success, one for failure — and returns whatever they return: a way to handle both cases in one expression. The services of Chatex mostly use plainif (!result.IsSuccess)checks; the playground program at the end of this topic usesMatch.
Result types in other languages
The idea comes from functional languages: Result<T, E> in Rust, Either in Haskell and Scala. .NET has no built-in result type, so projects write their own (as here) or use a library. The .editorconfig of topic 2 switches off two analyzer rules for exactly this file: CA1000 (static members on a generic type) and CA1716 (Error is a keyword in Visual Basic).
Step 4. Errors shared by several features
Do. Errors that belong to one feature live with it (ChatErrors, AuthErrors, …). Two are shared by several services:
cs
namespace Chatex.Core.Common;
public static class CommonErrors
{
public static Error QueryTooShort { get; } =
Error.Validation("query", "query_too_short", "Type at least 2 characters to search.");
public static Error AvatarNotFound { get; } = Error.NotFound("avatar_not_found", "There is no avatar.");
}The errors are static properties with an initializer ({ get; } = ...): created once, reused forever. Because Error is an immutable record, sharing one instance is safe.
Check
powershell
dotnet buildThe build succeeds with zero warnings. Chatex.Core still has no package of its own; Result and Error use only the base library.