PascalTurbo
PascalTurbo

Reputation: 2359

Render a status code when an error occured

When someone accesses my API with something different than an integer value, it should return a 400 Error.

My minimalized index method is:

def index
    @returnType = MyType.all

    if params["limit"].present?
        begin
            limit = Integer(limit)
        rescue Exception=>e
            render status: :bad_request
        end
     end

    respond_to do |format|
        format.json
    end
end

But, in the exception-case I get a AbstractController::DoubleRenderError.

The problem is, Rails doesn't stop the method at render, it continued with the respond_to part.

Upvotes: 0

Views: 67

Answers (1)

Undo
Undo

Reputation: 25697

You need to render and return:

if params["limit"].present?
    begin
        limit = Integer(limit)
    rescue Exception=>e
        render status: :bad_request
        return
    end
 end

This will render the error and then stop execution of the method.

Upvotes: 1

Related Questions