'What value should I return in catch?
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]
Solution 1:[1]
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
Solution 2:[2]
'CompanyController.Create(DtoCompany)': not all code paths return a value [API]
I can't understand is "what should I return?"
If in the try block there's already a return statement, you could put the other return at the end of the function, and this in order to avoid multiple returns if multiple exceptions need to be handled:
try
{
//somecode
return Ok();
}
catch(Exception ex)
{
Console.WriteLine("Error From Company-Create:", ex.Message);
}
return BadRequest();// add this code
Solution 3:[3]
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");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | musium |
| Solution 2 | Qing Guo |
| Solution 3 | Atrin Noori |
