2015-03-13 94 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 
相关问题