Skip to content

グローバルなエラーハンドリングの実装 #2

@YujiTani

Description

@YujiTani

ApplicationController` に一括してエラーハンドリングを行う

AIにはこんな感じに提案された

ruby:backend/app/controllers/application_controller.rb
   class ApplicationController < ActionController::API
     rescue_from ActiveRecord::RecordInvalid, with: :handle_record_invalid
     rescue_from ActiveRecord::RecordNotFound, with: :handle_record_not_found
     rescue_from StandardError, with: :handle_standard_error

     private

     def handle_record_invalid(exception)
       render json: {
         ok: false,
         request_id: SecureRandom.uuid,
         code: "RecordInvalid",
         message: "データの保存に失敗しました。",
         errors: exception.record.errors.full_messages
       }, status: :unprocessable_entity
     end

     def handle_record_not_found(exception)
       render json: {
         ok: false,
         request_id: SecureRandom.uuid,
         code: "RecordNotFound",
         message: "リソースが見つかりませんでした。"
       }, status: :not_found
     end

     def handle_standard_error(exception)
       Rails.logger.error(exception.message)
       Rails.logger.error(exception.backtrace.join("\n"))
       render json: {
         ok: false,
         request_id: SecureRandom.uuid,
         code: "InternalServerError",
         message: "内部サーバーエラーが発生しました。"
       }, status: :internal_server_error
     end
   end

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions