Handle and Return Error Message In API Calls

Prathamesh Shende 381 Reputation points
2022-04-10T13:44:50.557+00:00

Hi,
My project is in Blazor WASM and ASP.Net Core WebApi

I created crud api and add some business login, call into blazor.

// GET: api/Fiscals/5
[HttpGet("{id}")]
public async Task<ActionResult<Fiscal>> GetFiscal(int id)
{

        var fiscal = await _context.Fiscal.FindAsync(id);

        if (fiscal == null)
        {
            _logger.LogError("No fiscal found");
            return NotFound();
        }

        return fiscal;
    }

[HttpPost]
public async Task<ActionResult<Fiscal>> PostFiscal(Fiscal fiscal)
{
var fiscals = _context.Fiscals.ToList();

if(fiscals.Any(a=>a.Year == fiscal.Year)
{
error = new Error {
Code = 101,
Message = "Already exists"
};
}
else
{
_context.Fiscal.Add(fiscal);
await _context.SaveChangesAsync();

        return CreatedAtAction("GetFiscal", new { id = fiscal.ID }, fiscal);

}
}

On post method when inserting into db I checked is entry already available or not. If already exists then it will return error class. so the return type is fiscal class so It's not possible.
So for this I m managing this on Blazor Client side by calling get api then check is it exists or not and then call post api.
But this same I'm doing business logic and stuff on both side.

my question, is it possible to return error message into api so I can use it and call into front end and manage all logics in API side without changing return class?
or what will be the best approach?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,590 questions
{count} votes

3 answers

Sort by: Most helpful
  1. AgaveJoe 28,381 Reputation points
    2022-04-10T17:32:32.75+00:00

    my question, is it possible to return error message into api so I can use it and call into front end and manage all logics in API side without changing return class?

    Just follow openly published standards and return an HTTP status as covered in any beginning level Web API tutorial. For example....

    return BadRequest()   
    

    Or

    return BadRequest(new {message = "Missing input parameter."})  
    

    Controller action return types in ASP.NET Core web API

    1 person found this answer helpful.
    0 comments No comments

  2. Lohith GN 511 Reputation points
    2022-04-12T12:55:27.377+00:00

    @Prathamesh Shende

    As a developer of Web API, we usually follow the REST API paradigm. What that means is - we use HTTP as a backbone for all communication between client & server and we use the HTTP terminologies as the communication protocol.

    REST API endpoints usually are designed as below:
    GET /api/products - List products in system. Since this is a read the HTTP verb used is GET. The HTTP status code will be 200 if there was a successful retrieve. If we encounter any error on the server we send HTTP status code 50X
    GET /api/products/id - Get details of product with id. Since this is a read the HTTP verb used is GET. The HTTP status code will be 200 if there was a successful retrieve. If we encounter product not found it, we will send status code 404. If we encounter any error on the server we send HTTP status code 50X
    POST /api/products - Create product in the system. Since this is a write operation, the HTTP verb used is POST. The HTTP status code returned will be 201 if create was successful. If we encounter any error on the server we send HTTP status code 50X
    PUT /api/products/id - Update product in the system. Since this is a write operation, the HTTP verb used is POST. The HTTP status code returned will be 204 (No Content) if update was successful. If we encounter any error on the server we send HTTP status code 50X
    DELETE /api/products/id - Delete product in the system. Since this is a delete operation, the HTTP verb used is DELETE. The HTTP status code returned will be 204 (No Content) if delete was successful. If we encounter any error on the server we send HTTP status code 50X

    As you can see we already have the HTTP status codes for most of the scenario you can think of.

    Now coming to the consumer side or client side: The client/consumer will always make a HTTP call for any interaction with the server. Since the standard of communication is set and the HTTP status code returned is all industry standard based - it becomes easy for the client. The clients have to just check the HTTP Status code returned and take action appropriately. This is by far the typical usage pattern on clients/consumer side irrespective of technology stack - web/console/mobile/desktop applications.

    Hope this helps

    ----------

    Note: Please mark this as accepted answer if this solved your issue and upvote this answer for others benefit.

    0 comments No comments

  3. Bruce (SqlWork.com) 65,901 Reputation points
    2022-04-13T15:48:32.397+00:00

    webapi error handling is always a major design decision. there are also recoverable and non-recoverable errors. there may also be errors you have no control over, like network failure, or server failures.

    there are two camps. just use the status return values, which give a code and a text value. or a standard response, with status.

    a standard response would be like:

    public class BaseResponse<T>
    {
    public bool success {get; set;} = true;
    public string[] errors {get; set;}
    public T data {get; set;}
    }

    then actions return

    return new BaseResponse<MyModel> { data = model };

    even if you use standard response, the client will need to handle network errors. this is similar to the fetch() logic, which only throws errors with network, status codes are passed as valid.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.