You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BMRHandler.cs 2.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System.Net;
  2. using System.Net.Http;
  3. using System.Web.Http;
  4. using iiie.Logs.DataAccess;
  5. using iiie.Logs.DBO;
  6. namespace iiie.WebApiUtils.BusinessManager
  7. {
  8. /// <summary>
  9. /// Handle business manager results
  10. /// </summary>
  11. /// <typeparam name="T">Data type</typeparam>
  12. public class BMRHandler<T>
  13. {
  14. /// <summary>
  15. /// Converts ResultStatus codes to HttpStatusCodes codes
  16. /// </summary>
  17. /// <param name="status">The status code</param>
  18. /// <returns>The http code</returns>
  19. public static HttpStatusCode ResultStatusToHttp(ResultStatus status)
  20. {
  21. if (status == ResultStatus.LoginError)
  22. return HttpStatusCode.Unauthorized;
  23. if (status == ResultStatus.PermissionError)
  24. return HttpStatusCode.Forbidden;
  25. if (status == ResultStatus.InputError)
  26. return HttpStatusCode.BadRequest;
  27. if (status == ResultStatus.NotFound)
  28. return HttpStatusCode.NotFound;
  29. return HttpStatusCode.InternalServerError;
  30. }
  31. /// <summary>
  32. /// Returns a string corresponding to the error
  33. /// </summary>
  34. /// <param name="result">The result of the operation</param>
  35. /// <returns>The error string</returns>
  36. public static string OpResultToString(OpResult<T> result)
  37. {
  38. if (result.PublicDetails != null)
  39. return result.PublicDetails;
  40. if (result.Status == ResultStatus.LoginError)
  41. return "Bad username/password";
  42. if (result.Status == ResultStatus.PermissionError)
  43. return "You don\'t have the permission to do this action";
  44. if (result.Status == ResultStatus.InputError)
  45. return "Invalid data was provided";
  46. if (result.Status == ResultStatus.NotFound)
  47. return "Ressource not found";
  48. return "Internal error";
  49. }
  50. /// <summary>
  51. /// Handle business manager results
  52. /// </summary>
  53. /// <param name="result">The result to handle</param>
  54. /// <param name="request">The request to handle</param>
  55. /// <returns>The data to return to the user</returns>
  56. public static T Handle(OpResult<T> result, HttpRequestMessage request)
  57. {
  58. if (result.Status == ResultStatus.Success)
  59. return result.Data;
  60. result.Log();
  61. var msg = request.CreateErrorResponse(ResultStatusToHttp(result.Status), OpResultToString(result));
  62. throw new HttpResponseException(msg);
  63. }
  64. }
  65. }