Torihaji's Growth Diary

Little by little, no hurry.

Rails 、エラーの時に使うraiseの使い方!

はじめに

みなさん、こんにちは torihaziです

書き殴りメモです!

raiseの3種類の使い方

# パターン1
raise "エラーメッセージ"

# パターン2
raise ErrorClass, "エラーメッセージ"

# パターン3
raise ErrorClass.new("エラーメッセージ")
# シンプルな例
raise "Invalid value"

# エラークラスを指定する例
raise ArgumentError, "Invalid argument"

# 条件付きで発生させる例
raise "Invalid age" if age < 0

# 独自のエラークラスを使用する例
class MyCustomError < StandardError; end
raise MyCustomError, "Something went wrong"

大抵ApplicationControllerに書いてrescue_fromと合わせて使うそう!

このエラーが発生したらwithで指定したメソッドを発火させるみたいな!

なるほど!

class ApplicationController < ActionController::Base
  rescue_from StandardError, with: :handle_standard_error
  rescue_from ActiveRecord::RecordNotFound, with: :handle_not_found
  
  private
  
  def handle_standard_error(error)
    # エラーログを残したり
    Rails.logger.error(error.message)
    # JSONレスポンスを返したり
    render json: { error: error.message }, status: :internal_server_error
  end

  def handle_not_found(error)
    render json: { error: "Resource not found" }, status: :not_found
  end
end

終わりに

また一歩成長!

以上!