I've read (here) that it's not a good idea to do Try/Catch blocks and avoid exceptions in a Web API setting. However, if you want to catch and log errors as they happen in your app... wouldn't a try/catch be the best way to go about things? Here's an example of what I've done in my application - I'm curious if anyone has a better way. My ErrorHander class saves the error to the database and emails administrators the details of the error.
Controller
namespace MyApp.Controllers
{
[Route("api/[controller]")]
public class AuthController : Controller
{
private readonly IAuthRepository _repo;
private readonly IErrorHandler _errorHandler;
private AuthController(IAuthRepository repo, IErrorHandler errorHandler) {
_errorHandler = errorHandler;
}
[Authorize]
[HttpPut("changePassword")]
public async Task<IActionResult> ChangePassword(
[FromBody] UserForChangePasswordDto userForChangePasswordDto)
{
var userFromRepo = await _repo.Login(userForChangePasswordDto.Username,
userForChangePasswordDto.OldPassword, null);
try
{
//logic to update user's password and return updated user
return Ok(new { tokenString, user });
}
catch (Exception ex)
{
// emails error to Admin, saves it to DB, then returns HttpStatusCode
return await _errorHandler.HandleError(
HttpStatusCode.InternalServerError, Request, new Error
{
Message = ex.Message,
StackTrace = ex.StackTrace,
User = userFromRepo != null ? userFromRepo.Username : "Invalid User"
});
}
}
}
}
app.UseExceptionHandler. This is much easier. And then I can still use the same ErrorHandler class to give (and log) custom responses.