簡體   English   中英

如何返回 http 錯誤狀態代碼以及 class 中的自定義消息

[英]How to return http error status code along with custom message in a class

我想在 class 中返回帶有自定義消息的 https 錯誤狀態代碼。但是,每當我嘗試這樣做時,它都會說它無法從 IResult 轉換為我的 model class 員工。 在創建一個處理 sql 邏輯的 class 之前,我在 program.cs 文件中有如下內容,當我輸入一個數據庫中不存在的值時,它按預期工作。

app.MapGet("/employee/{id}", (ApplicationDbContext db, int id) =>
{
    var employee = db.Employee.Find(id);
    if (employee == null)
        return Results.NotFound("Employee not found");
    return Results.Ok(employee);        
});

現在創建一個單獨的 class 將所有邏輯放在一個文件中,我在 program.cs 文件中有以下內容,在單獨的文件中有邏輯。

app.MapGet("/employee/{id}", (IDataRepository dr, int id) =>
{
    return dr.GetEmployee(id);
});

現在在單獨的文件中:

 public Employee GetEmployee(int id)
        {
            var employee = _db.Employee.Find(id);
            if (employee == null)
            {
                return Results.NotFound("Employee not found!");
            }
            return employee;
        }

它建議對我的員工 model class 進行演員表。 當我輸入一個 id 時知道它不存在於數據庫中,它會給我一個轉換錯誤,說無法轉換兩者。 任何建議將不勝感激。

如果您想拆分代碼,我建議您在端點文件中保留 nofound 方法。 實際上,此邏輯與您的 GetEmployee 方法無關。 將來,如果您想在代碼的另一部分中重用 GetEmployee 邏輯,notfound 方法會給您帶來麻煩。

我的意思是就職責而言,您的方法 GetEmployee 正在檢索員工並返回狀態代碼(與員工無關)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM