1

In my Rocket web application I have a service that reads data from a MySQL database. At some point a NULL value appeared in a VARCHAR field - something my code wasn't expecting and as a result the tx.query_map() method started panicing. I don't like the fact that the mysql crate panics in such cases. But that only comes to show that panics can occur no matter how we write our code - we can never know when an external library will panic instead of returning an error value.

So my question is why does Rocket return a 200 OK status code in the response with an empty JSON array ([]) when the panic occurs, instead of returning some error status code like 500 for example? Should I do something explicit in my setup and if yes - what is it?

at54321
  • 8,726
  • 26
  • 46
  • 1
    Can you post a [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example)? Because by default Rocket v0.5-rc does exactly what you want: It returns a 500 status code if a handler panics. – HHK Jun 24 '21 at 18:18

2 Answers2

0

I was wrong. Rocket does respond with 500 Internal Server Error. The reason I was getting that weird 200 OK and empty JSON array response body was because the request was going through a proxy that had nothing to do with Rocket and Rust - of that I had completely forgotten, that's why I reported what I was seeing in Chrome's Network tab. And apparently the proxy was not handling those cases correctly.

BTW I am using Rocket 0.4.10

at54321
  • 8,726
  • 26
  • 46
-1

You could always use catch_unwind like this (example from docs):

use std::panic;

let result = panic::catch_unwind(|| {
    println!("hello!");
});
assert!(result.is_ok());

let result = panic::catch_unwind(|| {
    panic!("oh no!");
});
assert!(result.is_err());

But I would try to avoid this whenever possibly, panics are normally not meant to be "caught" and handled by your application. If the panic is caused by the mysql crate itself it may be a good idea to open an issue there.

F0X
  • 370
  • 4
  • 13
  • I am not sure how I can use that code to respond to the user's *request* with an error? As for your advice, resolving the specific issue is a separate matter. The point is that an application should handle panics, since they cannot be possibly avoided all the time. – at54321 Jun 24 '21 at 11:49
  • @at54321 if you really really need to handle a panic, then use the above shown function to catch a panic and convert it to an error, which you can then normally handle by logging it, returning the according HTTP status code, etc. Just to repeat myself, panics are in most situations not meant to be caught by you. You should obviously take measures to make sure your application is always available and can deal with unexpected problems like crashes, which could always occur. – F0X Jun 24 '21 at 20:31
  • Additionally as noted by a comment on your question, it seems as though rocket already does handle panics for you. – F0X Jun 24 '21 at 20:32