Table of contents
1.
Introduction
2.
What is Sinatra?
3.
Error Handling
4.
HTTP Responses and Status Codes
5.
Error Codes 
6.
Handling Errors in Sinatra
7.
Frequently Asked Questions
7.1.
What is Sinatra?
7.2.
Should I start by writing unit tests?
7.3.
How does Sinatra function?
7.4.
What exactly are Rails and Sinatra?
7.5.
Is Flask similar to Sinatra?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

Error Handling in Sinatra

Author Saksham Gupta
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Ruby developers may quickly create web apps with Sinatra, a Domain Specific Language. It maintains a meager list of capabilities and leaves it up to the designer to use the tools that are most appropriate for their use and the application. Any Rack-based application stack, including Rails, can be integrated with it. It is used by organizations like Apple, BBC, GitHub, LinkedIn, and others.
 

Error Handling in Sinatra

What is Sinatra?

Sinatra is used as a web framework that gives users the core essentials and abstractions to create straightforward and dynamic Ruby web applications. Before developing Sinatra applications, it is crucial to have a fundamental understanding of the Ruby programming language.

The advantage of using Sinatra over more powerful web frameworks like Rails is that it's easier to comprehend how an application's fundamental features operate. It would be more practical to transition to more complex tools, like Rails, after knowing how the essential elements function using a lightweight tool for constructing apps. MVC stands for Model-View-Controller in web applications.

In other words, MVC emphasizes the separation of logic in our program. Model View Controller is a software design pattern that separates the logic while creating an application.

Error Handling

The response and recovery processes from error circumstances that are present in a software application is referred to as error handling. In other words, it is the procedure for anticipating, detecting, and correcting communication, programming, and application failures.

HTTP Responses and Status Codes

Every time our web server responds to an HTTP request, in addition to sending content (the response's body), it also sends a status code that describes the request's outcome. This code provides information on whether the request was successful and how the client should proceed to your browser (or any other client).
The four different levels of codes

  • 2xx = Success is the usual outcome!
  • You've probably come across a 301 Resource Permanently Moved (redirection) at some point when you see the number 3xx.
  • Everyone has undoubtedly encountered a 404 error before. 4xx Indicates User Error.
  • The bad news is that 5xx = Service Error, which indicates that the server has collapsed.

 

Error Codes
 

Errors

 

  • Incorrect Request (400): User mistake or bad data, general
  • Unauthorized, code 401 (this area requires you to log in)
  • Not Found: 404 (bad URL)
  • Method Not Allowed, code 405 (wrong HTTP method)
  • Conflict, code 409 (i.e., trying to create the same resource with a PUT request)

 

Handling Errors in Sinatra

Sinatra handles mistakes in a more polite and conscientious manner toward the user of your application. By either gathering information about the mistake or even displaying a pleasant warning page to the consumers, you will learn how to manage unanticipated errors and take appropriate action. Sinatra's error handling is unbeatable. The format is the same as what our other handlers have used, and it is quite straightforward. 
 

  • Say you wish to prevent a 422 error, which stands for an unprocessable entity. You could define it as follows:
     
error 422 do
    { error: "You had an error" }
end


Sinatra will observe your return value and understand to run the handler for the "422" error code. This indicates that returning single integer values from your RESTful controllers is generally not a good idea, but you probably already don't.
 

  • To prevent 404 error,
     
get ‘/raise404’ do status 404 
     { error: "You had an error" }
end


You can also add a custom response body with body
 

  • To prevent 403 error

    You may further employ the 'stop' command in addition to these strategies. This will halt all other activities and trigger an immediate response. If, for instance, we require a particular parameter to be supplied, but it isn't sent, it is quite helpful.
     
get ‘/raise403’ do status 403
       {‘This is a 403 error’}
 end



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

if params[:name].nil?
halt 500, "my error message"
end
... do stuff end  ````

Frequently Asked Questions

What is Sinatra?

Sinatra is used as a web framework that gives users the core essentials and abstractions to create straightforward and dynamic Ruby web applications. Before developing Sinatra applications, it is crucial to have a fundamental understanding of the Ruby programming language.

Should I start by writing unit tests?

It is common practice to write the test first, followed by as much code as is required to pass it. It contributes to the practice of Test-Driven Development (TDD).

Bluefruit extensively uses TDD because it allows us to build the right product with minimal waste and redundancy.

How does Sinatra function?

The web server responds to a series of queries that Sinatra sends and receives. These requests are contained in a controller file, which is part of your program and communicates with the internet. A controller is a component of the MVC architectural design pattern (Models-Views-Controllers).

What exactly are Rails and Sinatra?

Rail is a framework for creating model-driven web applications, while Sinatra is a library for handling HTTP on the server side. Sinatra is an excellent tool for handling HTTP requests and responses. Rails are the way to go if you need full integration and as little boilerplate as possible.

Is Flask similar to Sinatra?

Sinatra is ideal for basic apps, much like Flask. Only 4 LOC of the actual Sinatra application is contained in a single Ruby source file, due to which Flask is used instead of libraries like Ruby on Rails. Sinatra is used since it allows you to start small and grow the application as necessary.

Conclusion

We have talked about Sinatra's Error Handling in this blog. We saw about different error codes and then how we can prevent them.

If you face any doubt, please comment, and we will love to answer your questions.

Want expertise in Ruby on rails for your next web development project? Check out our course.

Refer to our guided paths on Coding Ninjas Studio to learn about Data Structure and Algorithms, Competitive Programming, JavaScript, etc. Enroll in our courses and refer to our mock test available. Have a look at the interview experiences and interview bundle for placement preparations.

Happy Coding!

Thank You
Live masterclass