BaseController.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System;
  2. using Microsoft.AspNetCore.Mvc;
  3. using Microsoft.Extensions.Logging;
  4. using Quadarax.Foundation.Core.Business.Interface;
  5. using Quadarax.Foundation.Core.Data.Interface.Entity.Dto;
  6. namespace Quadarax.Foundation.Core.Web.Controllers
  7. {
  8. public abstract class BaseController<TController, TService> : ControllerBase
  9. where TController : ControllerBase
  10. where TService : IService
  11. {
  12. private ILogger<TController> _logger;
  13. protected TService Service { get; }
  14. protected BaseController(ILoggerFactory logger, TService service)
  15. {
  16. _logger = logger.CreateLogger<TController>() ?? throw new ArgumentNullException(nameof(logger));
  17. Service = service ?? throw new ArgumentNullException(nameof(service));
  18. }
  19. protected void ProcessException(ResultDto result, Exception exception)
  20. {
  21. }
  22. [HttpGet("test")]
  23. public ResultPlain Test()
  24. {
  25. return Call(() =>
  26. (ResultPlain)Service.Test()
  27. );
  28. }
  29. public TResult Call<TResult>(Func<TResult> block) where TResult : ResultDto, new()
  30. {
  31. var result = new TResult();
  32. try
  33. {
  34. return block();
  35. }
  36. catch (Exception e)
  37. {
  38. ProcessException(result, e);
  39. }
  40. return result;
  41. }
  42. protected void LogInfo(string message)
  43. {
  44. _logger.Log(LogLevel.Information, message);
  45. }
  46. protected void LogDebug(string message)
  47. {
  48. _logger.Log(LogLevel.Debug, message);
  49. }
  50. protected void LogTrace(string message)
  51. {
  52. _logger.Log(LogLevel.Trace, message);
  53. }
  54. protected void LogWarn(string message)
  55. {
  56. _logger.Log(LogLevel.Warning, message);
  57. }
  58. protected void LogWarn(string message, Exception exception)
  59. {
  60. _logger.Log(LogLevel.Warning, message);
  61. }
  62. protected void LogWarn(Exception exception)
  63. {
  64. _logger.Log(LogLevel.Warning, exception.ToString());
  65. }
  66. protected void LogError(string message)
  67. {
  68. _logger.Log(LogLevel.Error, message);
  69. }
  70. protected void LogError(string message, Exception exception)
  71. {
  72. _logger.Log(LogLevel.Error, message);
  73. }
  74. protected void LogError(Exception exception)
  75. {
  76. _logger.Log(LogLevel.Error, exception.ToString());
  77. }
  78. }
  79. }