我正在編寫一個基於Sinatra的API,並且想要使用API密鑰保護某些端點,在處理路由之前驗證密鑰。如何從前一個塊返回JSON響應
我明白爲什麼在before
塊不起作用拋出一個錯誤,因爲begin
/rescue
陳述沒有被調用呢,不過我要發送一個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