在ASP.NET中,依赖注入(DI)可以帮助我们更好地管理对象之间的依赖关系。要处理异常,我们可以使用以下几种方法:
public class UserService
{
private readonly IUserRepository _userRepository;
public UserService(IUserRepository userRepository)
{
_userRepository = userRepository;
}
public async Task<User> GetUserByIdAsync(int id)
{
try
{
return await _userRepository.GetUserByIdAsync(id);
}
catch (Exception ex)
{
// Log the exception
_logger.LogError(ex, "Error occurred while getting user by ID.");
// Return an appropriate error response
throw new UserNotFoundException("User not found.");
}
}
}
UserNotFoundException
类。public class UserNotFoundException : Exception
{
public UserNotFoundException() { }
public UserNotFoundException(string message) : base(message) { }
public UserNotFoundException(string message, Exception inner) : base(message, inner) { }
}
[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
private readonly UserService _userService;
public UsersController(UserService userService)
{
_userService = userService;
}
[HttpGet("{id}")]
public async Task<IActionResult> GetUserById(int id)
{
try
{
var user = await _userService.GetUserByIdAsync(id);
return Ok(user);
}
catch (UserNotFoundException ex)
{
// Log the exception
_logger.LogError(ex, "Error occurred while getting user by ID.");
// Return an appropriate error response
return NotFound(new { id });
}
catch (Exception ex)
{
// Log the exception
_logger.LogError(ex, "Error occurred while getting user by ID.");
// Return an appropriate error response
return StatusCode(500, "Internal server error.");
}
}
}
[ApiController]
[Route("api/[controller]")]
public class ErrorController : ControllerBase
{
private readonly ILogger<ErrorController> _logger;
public ErrorController(ILogger<ErrorController> logger)
{
_logger = logger;
}
[HttpGet]
public IActionResult Get()
{
try
{
throw new Exception("An error occurred while processing your request.");
}
catch (Exception ex)
{
// Log the exception
_logger.LogError(ex, "An error occurred while processing your request.");
// Return an appropriate error response
return StatusCode(500, new { message = "Internal server error." });
}
}
}
通过以上方法,我们可以在ASP.NET中使用依赖注入来处理异常。