This is how I would do it. Please also do not rescue from Exception
for the reasons detailed here – use StandardError
instead.
begin
if message.deliver
render json: { message: "Message sent successfully" }, status: 201
else
render json: { error: "Failure sending message" }, status: 401
end
rescue StandardError => e
if e.is_a?(ArgumentError) && e.message == "An SMTP To address is required to send a message."
render json: { error: "Invalid recipient address" }, status: 422
else
render json: { error: e.message }, status: 500
end
end