Skip to content

Handlers

Latest
Compare
Choose a tag to compare
@soveran soveran released this 01 Feb 11:08
· 11 commits to master since this release

This release adds status code handlers, a feature that will simplify many Syro applications.

When a request doesn't match, Syro will return a 404 status code with an empty body. It's a fine default because it doesn't make any assumptions, but in a production environment you want to return a helpful error message to the users. Up until now, the way to refine the 404 responses was to add a default block to each branch, for example:

App = Syro.new do
  get do
    # ...
  end

  on "foo" do
    get do
      # ...
    end

    default do
      res.text "Not found!"
    end
  end

  default do
    res.text "Not found!"
  end
end

In that application, only two requests will return a status code 200: GET / and GET /foo. Any other request will return a 404 error with the body "Not found!".

We had to define a default block for each branch, and if we want to deal with 404 status codes in a different way we can install a handler. The new version would look like this:

App = Syro.new do
  handle 404 do
    res.text "Not found!"
  end

  get do
    # ...
  end

  on "foo" do
    get do
      # ...
    end
  end
end

The external behavior will be the same, but the solution is perhaps more elegant. At any point, and in any branch, the handler can be replaced. For example, let's say you want a different error message when a user is not found:

App = Syro.new do
  handle 404 do
    res.text "Not found!"
  end

  # ...

  on "users" do
    on :id do
      handle 404 do
        res.text "User not found"
      end

      # ...
    end
  end
end

You can think about handlers as filters that will get executed just before finishing the request. Within those handlers you can do anything you would do in a regular block, for instance:

App = Syro.new do
  handle 404 do
    res.redirect "/wiki"
  end

  on "wiki" do
    # ...
  end
end

In this last example, the res.redirect statement will change the status code to 302. You can also add handlers for other status codes besides 404. You could even add handlers for status 200, but in that case, as it involves an extra method call, you will get a slight performance penalty.

The documentation covers other use cases and some edge conditions that you can abuse. Let me know if you run into any issues or if you detect something that's not clear enough.

Note: as the implementation uses the safe navigation operator &., Ruby > 2.3 is required to run this version.