mirror of
https://github.com/rojo-rbx/rojo.git
synced 2026-10-13 02:57:06 +00:00
Graceful errors instead of crashing (#1267)
This commit is contained in:
@@ -1,6 +1,27 @@
|
||||
use hyper::{header::CONTENT_TYPE, Body, Response, StatusCode};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Builds an HTTP response, falling back to an empty `500` response (rather than
|
||||
/// panicking) if the response could not be constructed. With constant headers
|
||||
/// and a valid status code this never actually fails, but routing every
|
||||
/// response through here means a malformed response can never crash the server.
|
||||
pub fn response(
|
||||
code: StatusCode,
|
||||
content_type: &'static str,
|
||||
body: impl Into<Body>,
|
||||
) -> Response<Body> {
|
||||
Response::builder()
|
||||
.status(code)
|
||||
.header(CONTENT_TYPE, content_type)
|
||||
.body(body.into())
|
||||
.unwrap_or_else(|err| {
|
||||
log::error!("Failed to build HTTP response: {}", err);
|
||||
let mut fallback = Response::new(Body::empty());
|
||||
*fallback.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
|
||||
fallback
|
||||
})
|
||||
}
|
||||
|
||||
pub fn msgpack_ok<T: Serialize>(value: T) -> Response<Body> {
|
||||
msgpack(value, StatusCode::OK)
|
||||
}
|
||||
@@ -12,18 +33,14 @@ pub fn msgpack<T: Serialize>(value: T, code: StatusCode) -> Response<Body> {
|
||||
.with_struct_map();
|
||||
|
||||
if let Err(err) = value.serialize(&mut serializer) {
|
||||
return Response::builder()
|
||||
.status(StatusCode::INTERNAL_SERVER_ERROR)
|
||||
.header(CONTENT_TYPE, "text/plain")
|
||||
.body(Body::from(err.to_string()))
|
||||
.unwrap();
|
||||
return response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"text/plain",
|
||||
err.to_string(),
|
||||
);
|
||||
};
|
||||
|
||||
Response::builder()
|
||||
.status(code)
|
||||
.header(CONTENT_TYPE, "application/msgpack")
|
||||
.body(Body::from(serialized))
|
||||
.unwrap()
|
||||
response(code, "application/msgpack", serialized)
|
||||
}
|
||||
|
||||
pub fn serialize_msgpack<T: Serialize>(value: T) -> anyhow::Result<Vec<u8>> {
|
||||
@@ -49,17 +66,13 @@ pub fn json<T: Serialize>(value: T, code: StatusCode) -> Response<Body> {
|
||||
let serialized = match serde_json::to_string(&value) {
|
||||
Ok(v) => v,
|
||||
Err(err) => {
|
||||
return Response::builder()
|
||||
.status(StatusCode::INTERNAL_SERVER_ERROR)
|
||||
.header(CONTENT_TYPE, "text/plain")
|
||||
.body(Body::from(err.to_string()))
|
||||
.unwrap();
|
||||
return response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"text/plain",
|
||||
err.to_string(),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
Response::builder()
|
||||
.status(code)
|
||||
.header(CONTENT_TYPE, "application/json")
|
||||
.body(Body::from(serialized))
|
||||
.unwrap()
|
||||
response(code, "application/json", serialized)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user