I just implemented a Try
catch
in my code, the error is because I have to return something in the catch
,
I can't understand is "what should I return?"
'CompanyController.Create(DtoCompany)': not all code paths return a value [API]
[HttpPost("create/")]
public async Task<ActionResult> Create([FromBody] DtoCompany dto_company)
{
try
{
var query = context.Companies.FirstOrDefault(x => x.rnc == dto_company.rnc);
if (query != null)
{
Company comp = mapper.Map<Company>(query);
context.Add(comp);
await context.SaveChangesAsync();
return Ok("Registro de compania exitoso");
}
else
{
return BadRequest($"Ya existe una compañia con este RNC: `{dto_company.rnc}`");
}
}
catch (Exception ex)
{
Console.WriteLine("Error From Company-Create:", ex.Message);
}
}
If I write the return
this, I getting an other error:
catch (Exception ex)
{
return Console.WriteLine("Error From Company-Create:", ex.Message);
}
Cannot implicitly convert type 'void' to 'Microsoft.AspNetCore.Mvc.ActionResult' [API]
CodePudding user response:
You should return an error telling your client what went wrong.
A good way to to this is to return Problem()
.
https://docs.microsoft.com/en-us/aspnet/core/web-api/handle-errors?view=aspnetcore-6.0
CodePudding user response:
You shouldn't return anything from the catch
part just a MessageBox
or Console.WriteLine
which you implemented on the first block...
Simply try catch
statement is to ask compiler to do something and if any error occurred in the code simply catch it and show it me using a MessageBox
or Console.WriteLine
Example:
try
{
sqlConnection conn = new sqlConnection(connection_string);
conn.Open();
}
catch (Exception ex)
{
if (ex.Message == "Certain specific error")
MessageBox.Show("Do not do it");
else
MessageBox.Show("Please do not do it");