Handling and Returning Errors

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.

HTTP Responses and Status Codes

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:

  • 2xx = Success - this is the norm!
  • 3xx = Redirect - you’ve probably encountered a 301 Resource Permanently Moved (redirection) at some point
  • 4xx = User error - everyone has definitely come across a 404 error before, right?
  • 5xx = Server error - this is the bad stuff; it means the server has fallen over.

Here’s a list of the most important status codes:

Success codes:

  • 200 - OK (the default)
  • 201 - Created
  • 202 - Accepted (often used for delete requests)

User error codes:

  • 400 - Bad Request (generic user error/bad data)
  • 401 - Unauthorized (this area requires you to log in)
  • 404 - Not Found (bad URL)
  • 405 - Method Not Allowed (wrong HTTP method)
  • 409 - Conflict (i.e. trying to create the same resource with a PUT request)

Handling Errors in Sinatra

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" }

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"
... do stuff end  ````

You can see that halt lets you send a status code and response body back.



The latest tutorials sent straight to your inbox.