Menu
CoddyTech

Chi tiết lỗi

Thuộc phần REST API trong hành trình ASP.NET Core của Coddy. Bài học 8 trên 20.

Phần nội dung 404 trống khiến client không biết lỗi gì đã xảy ra. Chi tiết sự cố (RFC 9457) là định dạng JSON chuẩn cho lỗi, được gửi với kiểu nội dung application/problem+json. Các phản hồi 400 của bạn đã dùng định dạng này. Trong API đơn hàng, ba dòng giúp mọi lỗi có cùng định dạng:

builder.Services.AddProblemDetails();
var app = builder.Build();

app.UseExceptionHandler();
app.UseStatusCodePages();

Bây giờ, GET /api/orders/7 sẽ trả lời 404 khi không tìm thấy đơn hàng, với nội dung:

{ "type": "https://tools.ietf.org/html/rfc9110#section-15.5.5",
  "title": "Not Found", "status": 404,
  "traceId": "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00" }

AddProblemDetails đăng ký dịch vụ tạo định dạng này. UseStatusCodePages bổ sung nội dung lỗi cho mọi phản hồi lỗi chưa có nội dung, dù đến từ Results.NotFound() hay từ đường dẫn không có tuyến nào khớp. UseExceptionHandler biến ngoại lệ chưa được xử lý thành lỗi 500. traceId được tạo mới cho mỗi yêu cầu và liên kết phản hồi với nhật ký của máy chủ.

challenge icon

Thử thách

Dễ

Đưa lỗi của trình theo dõi tác vụ về cùng một dạng để client đọc mọi lỗi theo cùng một cách.

  1. Trong Program.cs, thêm builder.Services.AddProblemDetails(); vào dòng ngay trước builder.Build().
  2. Ngay sau builder.Build(), thêm app.UseExceptionHandler();, rồi thêm app.UseStatusCodePages(); trước mọi endpoint.

Đừng thay đổi gì khác: các endpoint vẫn trả lời bằng Results.NotFound(), còn middleware sẽ điền phần nội dung phản hồi. Khi đó, GET /api/tasks/99 trả lời bằng mã 404, có kiểu nội dung application/problem+json và:

{ "type": "https://tools.ietf.org/html/rfc9110#section-15.5.5", "title": "Not Found", "status": 404, "traceId": "..." }

Thử ngay: nhấn Chạy rồi gửi GET /api/tasks/99: bạn sẽ nhận được mã 404 như trên. Gửi GET /api/projects, một đường dẫn không có route: phản hồi có cùng dạng. Gửi POST { "title": "" } đến /api/tasks: phản hồi mã 400 vẫn giữ errors và có thêm traceId.

Tự làm thử

using System.ComponentModel.DataAnnotations;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

var tasks = new List<TaskItem>
{
    new(1, "Write the project brief", false),
    new(2, "Book the meeting room", true),
    new(3, "Send the invoice", false),
};
var nextId = 4;

app.MapGet("/api/tasks", () => tasks);

app.MapGet("/api/tasks/{id:int}", (int id) =>
{
    var task = tasks.Find(t => t.Id == id);
    return task is null ? Results.NotFound() : Results.Ok(task);
});

app.MapPost("/api/tasks", (TaskInput input) =>
{
    var errors = Validation.Errors(input);
    if (errors is not null) return Results.ValidationProblem(errors);
    var task = new TaskItem(nextId++, input.Title, input.Done);
    tasks.Add(task);
    return Results.Created($"/api/tasks/{task.Id}", task);
});

app.MapPut("/api/tasks/{id:int}", (int id, TaskInput input) =>
{
    var errors = Validation.Errors(input);
    if (errors is not null) return Results.ValidationProblem(errors);
    var index = tasks.FindIndex(t => t.Id == id);
    if (index == -1) return Results.NotFound();
    tasks[index] = new TaskItem(id, input.Title, input.Done);
    return Results.Ok(tasks[index]);
});

app.MapPatch("/api/tasks/{id:int}", (int id, TaskPatch patch) =>
{
    var index = tasks.FindIndex(t => t.Id == id);
    if (index == -1) return Results.NotFound();
    var task = tasks[index];
    tasks[index] = task with
    {
        Title = patch.Title ?? task.Title,
        Done = patch.Done ?? task.Done,
    };
    return Results.Ok(tasks[index]);
});

app.MapDelete("/api/tasks/{id:int}", (int id) =>
{
    var removed = tasks.RemoveAll(t => t.Id == id);
    return removed == 0 ? Results.NotFound() : Results.NoContent();
});

app.Run();

record TaskItem(int Id, string Title, bool Done);
record TaskInput(
    [property: Required(ErrorMessage = "Title is required."), StringLength(80)] string Title,
    bool Done);
record TaskPatch(string? Title, bool? Done);
quiz iconTự kiểm tra

Bài học này có một bài trắc nghiệm ngắn. Bắt đầu bài học để trả lời và theo dõi tiến độ.

Tất cả bài học trong REST API