In the previous chapter, we wrote the code to post and retrieve courses through APIs, but what we demonstrated and tested were the happy path scenarios. In the real world, however, many types of failures can occur. The database server may be unavailable, the tutor ID provided in the request may be invalid, there may be a web server error, and so on. It is important that our web service be able to detect errors, handle them gracefully, and send a meaningful error message back to the user or client sending the API request. This is done through error handling, which is the focus of this chapter. Error handling is important not just for the stability of our web service, but also to provide a good user experience.
Figure 5.1 summarizes the error-handling approach we will adopt in this chapter. We’ll add custom error handling to our web service, unifying the different types of errors that can be encountered in the application. Whenever there is an invalid request or unexpected malfunction in the server code, the client will receive a meaningful and appropriate HTTP status code and error message. To achieve this, we will use a combination of the core Rust features for error handling and the features provided by Actix, while also customizing the error handling for our application.