handles_errors.rb 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. module ApplicationController::HandlesErrors
  3. extend ActiveSupport::Concern
  4. included do
  5. rescue_from StandardError, with: :internal_server_error
  6. rescue_from 'ExecJS::RuntimeError', with: :internal_server_error
  7. rescue_from ActiveRecord::RecordNotFound, with: :not_found
  8. rescue_from ActiveRecord::StatementInvalid, with: :unprocessable_entity
  9. rescue_from ActiveRecord::RecordInvalid, with: :unprocessable_entity
  10. rescue_from ActiveRecord::DeleteRestrictionError, with: :unprocessable_entity
  11. rescue_from ArgumentError, with: :unprocessable_entity
  12. rescue_from Exceptions::UnprocessableEntity, with: :unprocessable_entity
  13. rescue_from Exceptions::NotAuthorized, with: :unauthorized
  14. rescue_from Exceptions::Forbidden, with: :forbidden
  15. rescue_from Pundit::NotAuthorizedError, with: :pundit_not_authorized_error
  16. rescue_from Store::Provider::S3::Error, with: :unprocessable_entity
  17. end
  18. def not_found(e)
  19. logger.error e
  20. respond_to_exception(e, :not_found)
  21. http_log
  22. end
  23. def unprocessable_entity(e)
  24. logger.error e
  25. respond_to_exception(e, :unprocessable_entity)
  26. http_log
  27. end
  28. def internal_server_error(e)
  29. logger.error e
  30. respond_to_exception(e, :internal_server_error)
  31. http_log
  32. end
  33. def unauthorized(e)
  34. logger.info { e }
  35. error = humanize_error(e)
  36. response.headers['X-Failure'] = error.fetch(:error_human, error[:error])
  37. respond_to_exception(e, :unauthorized)
  38. http_log
  39. end
  40. def forbidden(e)
  41. logger.info { e }
  42. error = humanize_error(e)
  43. response.headers['X-Failure'] = error.fetch(:error_human, error[:error])
  44. respond_to_exception(e, :forbidden)
  45. http_log
  46. end
  47. def pundit_not_authorized_error(e)
  48. logger.info { e }
  49. # check if a special authorization_error should be shown in the result payload
  50. # which was raised in one of the policies. Fall back to a simple "Not authorized"
  51. # error to hide actual cause for security reasons.
  52. exception = e.policy&.custom_exception || Exceptions::Forbidden.new(__('Not authorized'))
  53. case exception
  54. when ActiveRecord::RecordNotFound
  55. not_found(exception)
  56. when Exceptions::UnprocessableEntity
  57. unprocessable_entity(exception)
  58. else
  59. forbidden(exception)
  60. end
  61. end
  62. private
  63. def respond_to_exception(e, status)
  64. status_code = Rack::Utils.status_code(status)
  65. respond_to do |format|
  66. format.json { render json: humanize_error(e), status: status }
  67. format.any do
  68. errors = humanize_error(e)
  69. @exception = e
  70. @message = errors[:error_human] || errors[:error] || param[:message]
  71. @traceback = !Rails.env.production?
  72. file = Rails.public_path.join("#{status_code}#{params[:controller] == 'mobile' ? '-mobile' : ''}.html").open('r')
  73. render inline: file.read, status: status, content_type: 'text/html' # rubocop:disable Rails/RenderInline
  74. end
  75. end
  76. end
  77. def humanize_error(e)
  78. data = { error: e.message }
  79. if (base_error = e.try(:record)&.errors&.messages&.find { |key, _| key.match? %r{[\w+.]?base} }&.last&.last)
  80. data[:error_human] = base_error
  81. elsif (first_error = e.try(:record)&.errors&.full_messages&.first)
  82. data[:error_human] = first_error
  83. elsif e.message.match?(%r{(already exists|duplicate key|duplicate entry)}i)
  84. data[:error_human] = __('This object already exists.')
  85. elsif e.message =~ %r{null value in column "(.+?)" violates not-null constraint}i || e.message =~ %r{Field '(.+?)' doesn't have a default value}i
  86. data[:error_human] = "Attribute '#{$1}' required!"
  87. elsif e.message == 'Exceptions::Forbidden'
  88. data[:error] = __('Not authorized')
  89. data[:error_human] = data[:error]
  90. elsif e.message == 'Exceptions::NotAuthorized'
  91. data[:error] = __('Authorization failed')
  92. data[:error_human] = data[:error]
  93. elsif [ActionController::RoutingError, ActiveRecord::RecordNotFound, Exceptions::UnprocessableEntity, Exceptions::NotAuthorized, Exceptions::Forbidden, Store::Provider::S3::Error, Authorization::Provider::AccountError].include?(e.class)
  94. data[:error_human] = data[:error]
  95. end
  96. if data[:error_human].present?
  97. data[:error] = data[:error_human]
  98. elsif !policy(Exceptions).view_details?
  99. error_code_prefix = "Error ID #{SecureRandom.urlsafe_base64(6)}:"
  100. Rails.logger.error "#{error_code_prefix} #{data[:error]}"
  101. data[:error] = "#{error_code_prefix} Please contact your administrator."
  102. end
  103. data
  104. end
  105. end