summaryrefslogtreecommitdiff
path: root/lib/opentox.rb
blob: 05a8a08a51f521aec659cfd66cbe9a29a43c856c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
require 'sinatra/base'
require "sinatra/reloader"

module OpenTox
  # Base class for OpenTox services
  # Errors are formated according to acccept-header
  # Non OpenTox::Errors (defined in error.rb) are handled as internal error (500), stacktrace is logged
  class Service < Sinatra::Base

    helpers Sinatra::UrlForHelper
    # use OpenTox error handling
    set :raise_errors, false
    set :show_exceptions, false
    set :static, false

    configure :development do
      register Sinatra::Reloader
    end

    error do
      # TODO: set actor, calling OT::Error with uri parameter does not work
      error = request.env['sinatra.error']
      #error.report.actor = "#{request.env['rack.url_scheme']}://#{request.env['HTTP_HOST']}#{request.env['REQUEST_URI']}"
      case request.env['HTTP_ACCEPT']
      when 'application/rdf+xml'
        content_type 'application/rdf+xml'
      when /html/
        content_type 'text/html'
      when "text/n3"
        content_type "text/n3"
      else
        content_type "text/turtle"
      end
      if error.respond_to? :report
        case request.env['HTTP_ACCEPT']
        when 'application/rdf+xml'
          body = error.report.to_rdfxml
        when /html/
          body = error.report.to_yaml
        when "text/n3"
          body = error.report.to_ntriples
        else
          body = error.report.to_turtle
        end
      else
        content_type "text/plain"
        body = error.message
        body += "\n#{error.backtrace}"
      end
      code = error.http_code if error.respond_to? :http_code
      code ||= 500
      halt code, error.report.to_turtle
    end
  end
end