actix-web icon indicating copy to clipboard operation
actix-web copied to clipboard

Can’t set content-type to JSON for Error responses

Open kaibyao opened this issue 7 years ago • 6 comments

Hi Nikolay, thank you for your hard work in building v1.0.

I'm running into an issue: for some reason the response being returned has a Content-Type of text/plain instead of application/json. Here's a minimal example. The dbg!() prints out the correct content type of application/json, but the response’s body has an actual content-type of text/plain. Am I doing something wrong?

What's the right way to return error structs as JSON values in 1.0?

// main.rs
use actix::System;
use actix_web::http::StatusCode;
use actix_web::web::{get, resource, HttpRequest, HttpResponse};
use actix_web::{App, HttpServer, ResponseError};
use futures::future::err;
use futures::Future;
use serde::Serialize;
use serde_json;
use std::fmt::{Display, Formatter, Result as FmtResult};
use std::io;

#[derive(Debug, Serialize)]
struct Error {
    msg: String,
    status: u16,
}

impl Display for Error {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        let err_json = serde_json::to_string(self).unwrap();
        write!(f, "{}", err_json)
    }
}

impl ResponseError for Error {
    fn error_response(&self) -> HttpResponse {
        let response = HttpResponse::build(StatusCode::from_u16(self.status).unwrap()).json2(self);

        dbg!(&response);

        response
    }
}

fn index(_: HttpRequest) -> impl Future<Item = HttpResponse, Error = Error> {
    err(Error {
        msg: "test".to_string(),
        status: 400,
    })
}

fn main() -> io::Result<()> {
    let sys = System::new("test-json-error");
    let ip_address = "127.0.0.1:8000";

    HttpServer::new(|| App::new().service(resource("/").route(get().to_async(index))))
        .bind(ip_address)
        .expect("Can not bind to port 8000")
        .start();

    println!("Running server on {}", ip_address);

    sys.run()
}

kaibyao avatar Jun 18 '19 17:06 kaibyao

Try something like this in response:

    HttpResponse::Ok()
        .content_type("application/json")
        .body(serde_json::to_string(data).unwrap())

https://github.com/actix/examples/blob/master/json/src/main.rs

max-frai avatar Jun 18 '19 17:06 max-frai

@max-frai Sorry, I didn't phrase my original question that well. Your solution works, in that replacing the contents of index() with the following code gives me the expected Content-Type:

futures::future::ok(HttpResponse::Ok()
        .content_type("application/json")
        .body("{}"))

// works as expected, outputs a content type of application/json with a body of "{}"

However, my original question of how to get an Error to output as JSON is still unsolved. Trying to return an error inside of index() still results in a text/plain content type, even though ResponseError has been implemented for the Error to output as a JSON response.

kaibyao avatar Jun 18 '19 19:06 kaibyao

rename error_response to render_response

fafhrd91 avatar Jun 19 '19 01:06 fafhrd91

That did it, thanks!

kaibyao avatar Jun 19 '19 05:06 kaibyao

@fafhrd91 this should be in doc somewhere ...

mrkaspa avatar Jul 16 '19 15:07 mrkaspa

@mrkaspa could you create Pr?

fafhrd91 avatar Jul 17 '19 02:07 fafhrd91