handles_errors.rb 4.7 KB

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