2017-04-19 1 views
0

Sinatra 기반 API를 작성 중이며 특정 끝점을 API 키로 보호하고 경로가 처리되기 전에 키의 유효성을 검사하려고합니다. 작동하지 않습니다 before 블록에서 오류를 던지는 이유 begin/rescue 제표가 아직 호출되지 않았기 때문에이전 블록에서 JSON 응답을 반환하는 방법

나는 그러나 내가 JSON 응답이 오류 메시지와 함께 다시 클라이언트로 전송하려면, 이해 JSON 객체.

어떻게하면됩니까?

namespace '/v1/sponser/:key' do 

    before do 
    if APIHelper.valid_key?(params[:key]) == false 
     throw 'Error, invalid API key' 
     # is it possible to return a JSON response from the before statement here? 
    end 
    end 

    get '/test' do 
    begin 
     json status: 200, body: 'just a test' 
    rescue => error 
     json status: 404, error: error 
    end 
    end 

end 

답변

1

나는 halt 사용을 고려합니다 :

before do 
    unless APIHelper.valid_key?(params[:key]) 
    halt 404, { 'Content-Type' => 'application/json' }, 
       { error: 'Error, invalid API key' }.to_json 
    end 
end 

get '/test' do 
    json status: 200, body: 'just a test' 
end 
0

당신은 특정 코드, 몸과 헤더 응답을 반환하는 halt 방법을 사용할 수 있습니다. 그래서 다음과 같습니다 : before do halt 401, {'Content-Type' => 'application/json'}, '{"Message": "..."}' end 일부 서비스를 제공하는 다른 URL로 리디렉션 할 수 있습니다.

관련 문제