Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sinatra redirect on error

I'm having problem with redirecting on error in Sinatra modular app. I'm deploying on Heroku and when there is an error, application dies.

I'd like it to catch this error, redirect to error page and operate normally.

I've set in my base class things as below:

set :raise_errors, false

and

error do
    redirect to('/')
end

but when I raise error from within route block it just goes to standard Sinatra error page.

What I need to do to catch my errors and redirect?

like image 402
grafthez Avatar asked Jun 24 '26 02:06

grafthez


1 Answers

You also need

set :show_exceptions, false

Here's a simple demo

require "sinatra"

class App < Sinatra::Base

    set :raise_errors, false
    set :show_exceptions, false

    get '/' do
        return 'Hello, World!'
    end

    get '/error' do
        return 'You tried to divide by zero!'
    end

    get '/not-found' do
        return 'There is nothing there'
    end

    get '/raise500' do
        raise 500
    end

    get '/divide-by-zero' do
        x = 5/0
    end

    error do
        redirect to('/')
    end

    error 404 do
        redirect to('/not-found')
    end

    error ZeroDivisionError do
        redirect to('/error')
    end

end

Without :show_exceptions set /raise500 and /divide-by-zero return the generic Sinatra error page, but with it they redirect as you would expect.

like image 97
Sean Redmond Avatar answered Jun 26 '26 22:06

Sean Redmond