2010-09-12 35 views
73

Có cách nào để bắt tất cả các trường hợp ngoại lệ uncatched trong một bộ điều khiển đường ray, như thế này:Catch tất cả các trường hợp ngoại lệ trong một bộ điều khiển đường ray

def delete 
    schedule_id = params[:scheduleId] 
    begin 
    Schedules.delete(schedule_id) 
    rescue ActiveRecord::RecordNotFound 
    render :json => "record not found" 
    rescue ActiveRecord::CatchAll 
    #Only comes in here if nothing else catches the error 
    end 
    render :json => "ok" 
end

Cảm ơn bạn

Trả lời

75
begin 
    # do something dodgy 
rescue ActiveRecord::RecordNotFound 
    # handle not found error 
rescue ActiveRecord::ActiveRecordError 
    # handle other ActiveRecord errors 
rescue # StandardError 
    # handle most other errors 
rescue Exception 
    # handle everything else 
    raise 
end 
+25

Không phải là quy tắc KHÔNG BAO GIỜ bắt ngoại lệ? – RonLugge

+1

nhưng làm thế nào tôi có thể bắt tất cả các loại trong khối 'rescue => e'? – Matrix

+4

@RonLugge nó phụ thuộc hoàn toàn vào tình hình trong tầm tay. áp dụng "không bao giờ" như một quy tắc của ngón tay cái là một ý tưởng tồi. –

9

rescue không có đối số sẽ giải cứu bất kỳ lỗi.

Vì vậy, bạn sẽ muốn:

def delete 
    schedule_id = params[:scheduleId] 
    begin 
    Schedules.delete(schedule_id) 
    rescue ActiveRecord::RecordNotFound 
    render :json => "record not found" 
    rescue 
    #Only comes in here if nothing else catches the error 
    end 
    render :json => "ok" 
end 
+6

câu hỏi thiu, nhưng câu trả lời này là không chính xác. giải quyết mà không có đối số chỉ xử lý StandardError http://robots.thoughtbot.com/rescue-standarderror-not-exception – karmajunkie

178

Bạn cũng có thể xác định một phương pháp rescue_from.

class ApplicationController < ActionController::Base 
    rescue_from ActionController::RoutingError, :with => :error_render_method 

    def error_render_method 
    respond_to do |type| 
     type.xml { render :template => "errors/error_404", :status => 404 } 
     type.all { render :nothing => true, :status => 404 } 
    end 
    true 
    end 
end 

Tùy thuộc vào mục tiêu của bạn là gì, bạn cũng có thể xem xét KHÔNG xử lý ngoại lệ trên cơ sở mỗi bộ điều khiển. Thay vào đó, hãy sử dụng thứ gì đó giống như đá quý exception_handler để quản lý các câu trả lời cho các ngoại lệ một cách nhất quán. Như một phần thưởng, cách tiếp cận này cũng sẽ xử lý các ngoại lệ xảy ra ở lớp trung gian, như yêu cầu phân tích cú pháp hoặc lỗi kết nối cơ sở dữ liệu mà ứng dụng của bạn không nhìn thấy. Các đá quý exception_notifier cũng có thể được quan tâm.

+3

Điều này thậm chí còn tiện dụng hơn vì nó cho phép bắt ngoại lệ theo cách DRY. – m33lky

+0

Và nếu tôi sử dụng rescue_from không có tham số? sẽ hành xử giống như giải cứu? bắt tất cả các lỗi? – minohimself

+2

Không phải là thực tế tồi để 'rescue_from Exception'? Sự hiểu biết của tôi là tốt hơn để giải cứu khỏi 'StandardError', vì vậy những thứ như' SyntaxError' và 'LoadError' không bị bắt gặp. – lobati

19

Bạn có thể bắt ngoại lệ theo loại:

rescue_from ::ActiveRecord::RecordNotFound, with: :record_not_found 
rescue_from ::NameError, with: :error_occurred 
rescue_from ::ActionController::RoutingError, with: :error_occurred 
# Don't resuce from Exception as it will resuce from everything as mentioned here "http://stackoverflow.com/questions/10048173/why-is-it-bad-style-to-rescue-exception-e-in-ruby" Thanks for @Thibaut Barrère for mention that 
# rescue_from ::Exception, with: :error_occurred 

protected 

def record_not_found(exception) 
    render json: {error: exception.message}.to_json, status: 404 
    return 
end 

def error_occurred(exception) 
    render json: {error: exception.message}.to_json, status: 500 
    return 
end 
+2

Cẩn thận không giải cứu trực tiếp từ 'Ngoại lệ'; xem http://stackoverflow.com/questions/10048173/why-is-it-bad-style-to-rescue-exception-e-in-ruby –

0

Trên thực tế, nếu bạn thực sự muốn bắt mọi thứ, bạn chỉ cần tạo ứng dụng ngoại lệ của riêng mình, mà cho phép của bạn tùy chỉnh các hành vi đó thường được xử lý bởi PublicExceptions middleware: https://github.com/rails/rails/blob/4-2-stable/actionpack/lib/action_dispatch/middleware/public_exceptions.rb

Một bó của đá quý câu trả lời phần khác mà làm điều này cho bạn, nhưng thực sự không có lý do gì bạn không thể chỉ nhìn vào chúng và tự làm.

Thông báo trước: đảm bảo bạn không bao giờ nêu ngoại lệ trong trình xử lý ngoại lệ của mình. Nếu bạn nhận được một FAILSAFE_RESPONSE xấu xí https://github.com/rails/rails/blob/4-2-stable/actionpack/lib/action_dispatch/middleware/show_exceptions.rb#L4-L22

BTW, hành vi trong bộ điều khiển xuất phát từ rescuable: https://github.com/rails/rails/blob/4-2-stable/activesupport/lib/active_support/rescuable.rb#L32-L51

Các vấn đề liên quan