Skip to content

Commit

Permalink
Inject a logger to record information whenever an exception occurs
Browse files Browse the repository at this point in the history
  • Loading branch information
Ahmed-Ghanam committed Oct 8, 2024
1 parent 30f5cea commit 6c23549
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 29 deletions.
41 changes: 17 additions & 24 deletions src/Altinn.Profile/Controllers/ContactDetailsController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace Altinn.Profile.Controllers;

Expand All @@ -20,15 +21,20 @@ namespace Altinn.Profile.Controllers;
[Route("profile/api/v1/contact/details")]
public class ContactDetailsController : ControllerBase
{
private readonly ILogger<ContactDetailsController> _logger;
private readonly IContactDetailsRetriever _contactDetailsRetriever;

/// <summary>
/// Initializes a new instance of the <see cref="ContactDetailsController"/> class.
/// </summary>
/// <param name="logger">The logger instance used for logging.</param>
/// <param name="contactDetailsRetriever">The use case for retrieving the contact details.</param>
/// <exception cref="ArgumentNullException">Thrown when the <paramref name="contactDetailsRetriever"/> is null.</exception>
public ContactDetailsController(IContactDetailsRetriever contactDetailsRetriever)
/// <exception cref="ArgumentNullException">
/// Thrown when the <paramref name="logger"/> or <paramref name="contactDetailsRetriever"/> is null.
/// </exception>
public ContactDetailsController(ILogger<ContactDetailsController> logger, IContactDetailsRetriever contactDetailsRetriever)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_contactDetailsRetriever = contactDetailsRetriever ?? throw new ArgumentNullException(nameof(contactDetailsRetriever));
}

Expand All @@ -46,39 +52,26 @@ public ContactDetailsController(IContactDetailsRetriever contactDetailsRetriever
[ProducesResponseType(typeof(ContactDetailsLookupResult), StatusCodes.Status200OK)]
public async Task<ActionResult<ContactDetailsLookupResult>> PostLookup([FromBody] UserContactPointLookup request)
{
try
if (request?.NationalIdentityNumbers == null || request.NationalIdentityNumbers.Count == 0)
{
if (request == null)
{
return BadRequest();
}

if (request.NationalIdentityNumbers == null)
{
return BadRequest();
}

if (request.NationalIdentityNumbers.Count == 0)
{
return BadRequest();
}
return BadRequest("National identity numbers cannot be null or empty.");
}

try
{
var result = await _contactDetailsRetriever.RetrieveAsync(request);

return result.Match<ActionResult<ContactDetailsLookupResult>>(
success =>
{
if (success.MatchedContactDetails.Count != 0)
{
return Ok(success);
}
return NotFound();
return success.MatchedContactDetails.Count > 0 ? Ok(success) : NotFound();
},
noMatch => NotFound());
}
catch
catch (Exception ex)
{
_logger.LogError(ex, "An error occurred while retrieving contact details.");

return Problem("An unexpected error occurred.");
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System;
using System.Threading.Tasks;

using Altinn.Profile.Controllers;
Expand All @@ -8,6 +7,7 @@

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

using Moq;

Expand All @@ -18,12 +18,14 @@ namespace Altinn.Profile.Tests.IntegrationTests.API.Controllers;
public class ContactDetailsControllerTests
{
private readonly ContactDetailsController _controller;
private readonly Mock<ILogger<ContactDetailsController>> _loggerMock;
private readonly Mock<IContactDetailsRetriever> _mockContactDetailsRetriever;

public ContactDetailsControllerTests()
{
_loggerMock = new Mock<ILogger<ContactDetailsController>>();
_mockContactDetailsRetriever = new Mock<IContactDetailsRetriever>();
_controller = new ContactDetailsController(_mockContactDetailsRetriever.Object);
_controller = new ContactDetailsController(_loggerMock.Object, _mockContactDetailsRetriever.Object);
}

[Fact]
Expand All @@ -44,7 +46,7 @@ public async Task PostLookup_ReturnsBadRequestResult_WhenRequestIsInvalid()
}

[Fact]
public async Task PostLookup_ReturnsInternalServerErrorResult_WhenExceptionOccurs()
public async Task PostLookup_ReturnsInternalServerErrorResult_LogError_WhenExceptionOccurs()
{
// Arrange
var request = new UserContactPointLookup
Expand All @@ -53,14 +55,24 @@ public async Task PostLookup_ReturnsInternalServerErrorResult_WhenExceptionOccur
};

_mockContactDetailsRetriever.Setup(x => x.RetrieveAsync(request))
.ThrowsAsync(new System.Exception("Test exception"));
.ThrowsAsync(new Exception("Test exception"));

// Act
var response = await _controller.PostLookup(request);

// Assert
var problemResult = Assert.IsType<ObjectResult>(response.Result);

Assert.Equal(StatusCodes.Status500InternalServerError, problemResult.StatusCode);

_loggerMock.Verify(
x => x.Log(
LogLevel.Error,
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((v, t) => v.ToString().Contains("An error occurred while retrieving contact details.")),
It.IsAny<Exception>(),
It.Is<Func<It.IsAnyType, Exception, string>>((v, t) => true)),
Times.Once);
}

[Fact]
Expand Down

0 comments on commit 6c23549

Please sign in to comment.