2015-03-13 90 views
-1

我有以下errors_controller.rb::的ActionView ----- MissingTemplate缺少模板消息/顯示

class ErrorsController < ActionController::Base 
layout 'bare' 

def show 
return render_error params[:id], :ok 
end 

def index 
    request.format.to_s.downcase == 'application/json' ? json_error : html_error 
    return 
end 

private 

def exception 
    env['action_dispatch.exception'] 
end 

def html_error 
    if exception.nil? 
    render_error 404 
    else 
    render_error 500 
    end 
end 

def json_error 
    if exception.nil? 
    render json: error_hash(:resource_not_found), status: 404 
    else 
    render json: error_hash(:internal_server_error), status: 500 
    end 
end 

def error_hash(code) 
    { 
    errors: [ 
     { 
     message: I18n.t("errors.api.#{code}"), 
     code: code 
     } 
    ] 
    } 
end 

def render_error(code, status_type = nil) 
    @error = ErrorMessage.new(code, status_type) 
    render @error.partial, status: @error.status 
end 
end 

當請求作出/api/test.xml 它給了我

ActionView::MissingTemplate at /api/test.xml 
Missing template messages/show with {:locale=>[:en], :formats=>[:xml],  :handlers=>[:erb, :builder, :raw, :ruby, :haml]} 

我不想做

rescue_from(ActionController::MissingTemplate) 

由於這將處理所有的行動中失蹤模板錯誤,即使網址中存在一些拼寫錯誤。

我希望有一個健康的方法拋出的任何請求404(.XML,.JPEG,......)

嘗試

我嘗試添加一個before_filter仍然給我相同錯誤。

我在application.rb中添加了config.action_dispatch.ignore_accept_header = true,仍然沒有運氣。

任何人都可以告訴我一些方向嗎?謝謝你在前進

+0

'我希望有一個健康的方法拋出一個404的任何請求(.XML,.JPEG,.....)' - 我想,你希望你的網站不時還回其他的東西?如果是這樣,哪些格式是允許的? – BroiSatse 2015-03-13 15:55:57

+0

那麼說'test.json'的請求會給出'404',因爲它沒有找到。這很好。但是,如果向除json或html之外的任何文件發出請求,它現在會給出'500'。我希望它仍然會拋出一個'404'。 – user3438489 2015-03-13 15:58:39

回答

1

你可以這樣做:

def render_error(code, status_type = nil) 
    @error = ErrorMessage.new(code, status_type) 
    respond_to do |format| 
    format.any(:html, :json) { render @error.partial, status: @error.status } 
    format.any { head 404, "content_type" => 'text/plain' } 
    end 
end 
相關問題