1. Creating a basic Sinatra Project
Building your first basic Sinatra project
Guides, tutorials and labs to accompany CMU's Programming for Online Prototypes (49-714).
Everything you need to know about building microservices for the web with Ruby and Sinatra.
Sometimes things go wrong. And you want to be able to handle them. Sinatra makes this super simple. Before we do that. Let’s cover some basics of HTTP Responses.
As part of every response to a HTTP Request our webserver will not only send content (the body of the response) but also includes status code that explains what happened with the request. This code tells your browser (or any other client) whether or not the request was successful and how the client should proceed.
There are four different levels of codes:
Here’s a list of the most important status codes:
Success codes:
User error codes:
You can’t beat error handling in Sinatra. It’s so simple, and follows the same format as our other handlers have followed. Let’s say you want to catch a 422
error – that means unprocessable entity. Here’s how you would define it:
error 422 do
{ error: "You haz an error" }
end
Now if you want to manually throw that error from a controller, you would do that like this:
````# Unprocessable Entity
get ‘/’ do return 422 end
Sinatra will see your return value and know to call the `422` error code handler. This means that you probably shouldn’t return single integer values from your RESTful controllers – but you probably don’t do that anyway.
You can also be specific that you want to return the status using the `status` keyword.
get ‘/raise404’ do status 404 end
You can also add a custom response body with body
get ‘/raise403’ do status 403 body ‘This is a 403 error’ end
In addition to these approaches, you can also use the `halt` command. This will stop everything else from happening and immediately return a response. It's really useful if, for example, we need a specific parameter to be passed and it isn't sent
get ‘/raise403’ do
if params[:name].nil?
halt 500, "my error message"
end
... do stuff end ````
You can see that halt
lets you send a status code and response body back.
This series guides you through creating your first Sinatra project and some of the features it offers for creating web-delivered apps
Building your first basic Sinatra project
Building your first basic Sinatra project
Routing with HTTP Methods explained
How to include named parameters in defined routes
Storing User Information in Sessions
How to return a HTTP error response
Using configuration blocks to store application wide variables