简体   繁体   中英

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

I am wanting to return an https error status code with a custom message in a class. However, whenever I try to do so it says it is unable to convert from IResult to my model class employee. Prior to creating a class that handles the logic for sql I had it as the following in the program.cs file which worked as expected when I entered a value that did not exist in the db.

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);        
});

Now creating a separate class to have all the logic in one file I have the following in the program.cs file and the logic in the separate file.

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

now in the separate file:

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

It suggested a cast to my model class, employee. When I enter an id knowing that it does not exist in the db it gives me a casting error saying cannot convert the two. Any suggestions would be greatly appreciated.

If you want to split your code, I suggest you to keep the nofound method on your endpoint file. Indeed, this logic has no relation with your GetEmployee method. In the future, if you want to reuse the GetEmployee logic in another part of your code, the notfound method will give you a problem.

I mean in terms of responsibilities, your method GetEmployee is retrieving the employees and returning the status code (no relation with employees).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM