Reporting error string from controller to the angular client

Viewed 27

I have a controller method from which I would like to return to my angular client some error condition when account object is null. I used exception below and it works, but is there a better way of reporting error string to the angular client then the below one.

[Authorize]
[HttpPost("get-schedule-from-pool/{id}")]
public ActionResult<AccountResponse> GetScheduleFromPool(int id, UpdateScheduleRequest scheduleReq)
{
    // users can update their own account and admins can update any account
    if (id != Account.Id && Account.Role != Role.Admin)
        return Unauthorized(new { message = "Unauthorized" });

    var account = _accountService.GetScheduleFromPool(id, scheduleReq);
    if(account == null)
    {
        // Request.Body.
        // return HttpError("Function :" + scheduleReq.UserFunction + " for date: " + scheduleReq.Date + " already taken");
        
        throw new Exception("Sample exception.");
    }
    
    return Ok(account);
}
1 Answers

If you want to return a error message or error code to the client there's a few ways to do it. Using StatusCode:

return  StatusCode(StatusCodes.Status500InternalServerError,"Details");

or

return StatusCode(500,"Details")

Or using the default wrappers:

return Problem("Details");

Here a list of all error codes and what they mean.

Related