0

I'm making a save to the database. But an error occurs during the save process. When I catch it with try-catch block like below, it doesn't give detailed information.

try{
    //save to database
}
catch (Exception ex){
    Console.WriteLine(ex.message);
}

But if I return InnerException.Message it is returning quite detailed information.

My question is does it make sense in terms of security for me to return an InnerException.Message, not an ex.Message, to the end user in WebAPI?

Or do I have to manually catch the relevant error and return? If so can I get a hint?

serdar
  • 9
  • 1
  • Generally you do not want to return exception details to the user. And do not count on the outer exception having little detail. You may catch some other exception that does have a lot of detail. – Crowcoder Jun 23 '22 at 11:27
  • API should return error message relevant to the user. You should not expose the original error message to the API client. example- If you encounter error due to duplicate keys then error should be `record already exists` – Chetan Jun 23 '22 at 11:27

1 Answers1

0

There is no single answer to this. Giving the full exception can present multiple infosec problems. You could create a UserFacingException : Exception, and when your code throws an exception that is OK to repeat to the user: throw that one (or a specific subclass of that one). This includes places where your code might itself catch a more specific exception, and report it upwards, for example:

catch (SqlException sql) when (sql.ErrorCode = ...) // unique constraint violation
{
    throw new UserFacingException("Username already exists", sql);
}

Then you could do:

try
{
    // whatever
}
catch (UserFacingException uex)
{
    Console.WriteLine(uex.Message); // TODO: to user, not console
}
catch (Exception ex)
{
    Log(ex);
    Console.WriteLine("An unknown error occurred"); // TODO: to user, not console
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900